stream: support ArrayBufferView in Utf8Stream write() buffer mode · nodejs/node@81e4ac4 · GitHub
Skip to content

Commit 81e4ac4

Browse files
agape1225aduh95
authored andcommitted
stream: support ArrayBufferView in Utf8Stream write() buffer mode
Utf8Stream#write() in 'buffer' content mode only accepted Buffer instances, even though the underlying implementation only needs byte-addressable data. This accepts any ArrayBufferView (TypedArray, DataView) and reinterprets it as a Buffer over the same bytes (without copying), so callers no longer need to wrap other typed arrays in Buffer.from() themselves. Views are normalized to a Buffer at the single entry point (#writeBuffer), using byteOffset/byteLength rather than the view's element-count length, so that internal length bookkeeping used by mergeBuf()/Buffer.concat() and the write-release logic keeps operating on real byte counts. This mirrors the existing pattern in zlibBuffer() (lib/zlib.js). Signed-off-by: agape1225 <49804691+agape1225@users.noreply.github.com> PR-URL: #65301 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Matteo Collina <matteo.collina@gmail.com>
1 parent ab93a3d commit 81e4ac4

3 files changed

Lines changed: 111 additions & 4 deletions

File tree

‎doc/api/fs.md‎

Lines changed: 2 additions & 2 deletions

‎lib/internal/streams/fast-utf8-stream.js‎

Lines changed: 11 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,10 @@ const {
1919
Buffer,
2020
} = require('buffer');
2121

22+
const {
23+
isArrayBufferView,
24+
} = require('internal/util/types');
25+
2226
const fs = require('fs');
2327
const EventEmitter = require('events');
2428
const path = require('path');
@@ -803,9 +807,14 @@ class Utf8Stream extends EventEmitter {
803807
throw new ERR_INVALID_STATE('Utf8Stream is destroyed');
804808
}
805809

806-
// TODO(@jasnell): Support any ArrayBufferView type here, not just Buffer.
810+
if (!isArrayBufferView(data)) {
811+
throw new ERR_INVALID_ARG_TYPE('data', ['Buffer', 'TypedArray', 'DataView'], data);
812+
}
807813
if (!Buffer.isBuffer(data)) {
808-
throw new ERR_INVALID_ARG_TYPE('data', 'Buffer', data);
814+
// Reinterpret the view as a byte-oriented Buffer without copying, so that
815+
// `data.length` below (and everywhere else `bufs`/`lens` are consumed)
816+
// reflects the byte length rather than the element count.
817+
data = Buffer.from(data.buffer, data.byteOffset, data.byteLength);
809818
}
810819

811820
const len = this.#len + data.length;
Lines changed: 98 additions & 0 deletions

0 commit comments

Comments
 (0)