stream: copy SAB-backed chunks in iter consumers · nodejs/node@d4dfb66 · GitHub
Skip to content

Commit d4dfb66

Browse files
trivikraduh95
authored andcommitted
stream: copy SAB-backed chunks in iter consumers
Ensure bytes() copies single chunks backed by SharedArrayBuffer so arrayBuffer() and arrayBufferSync() return ArrayBuffer instances as specified. Signed-off-by: Kamat, Trivikram <16024985+trivikr@users.noreply.github.com> Assisted-by: openai:gpt-5.5 PR-URL: #64382 Fixes: #64381 Reviewed-By: James M Snell <jasnell@gmail.com> Reviewed-By: Mattias Buelens <mattias@buelens.com>
1 parent 7fd5f66 commit d4dfb66

3 files changed

Lines changed: 22 additions & 17 deletions

File tree

lib/internal/streams/iter/consumers.js

Lines changed: 6 additions & 8 deletions

lib/internal/streams/iter/utils.js

Lines changed: 12 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -203,6 +203,12 @@ function allUint8Array(chunks) {
203203
return true;
204204
}
205205

206+
function copyBytes(chunk) {
207+
const copy = new Uint8Array(TypedArrayPrototypeGetByteLength(chunk));
208+
TypedArrayPrototypeSet(copy, chunk);
209+
return copy;
210+
}
211+
206212
/**
207213
* Concatenate multiple Uint8Arrays into a single Uint8Array.
208214
* @param {Uint8Array[]} chunks
@@ -220,16 +226,15 @@ function concatBytes(chunks) {
220226
// If non-zero offset, skip the remaining buffer checks.
221227
if (TypedArrayPrototypeGetByteOffset(chunk) === 0) {
222228
const buf = TypedArrayPrototypeGetBuffer(chunk);
223-
// SharedArrayBuffer is not available in primordials, so use
224-
// direct property access for its byteLength.
225-
const bufByteLength = isSharedArrayBuffer(buf) ?
226-
buf.byteLength :
227-
ArrayBufferPrototypeGetByteLength(buf);
228-
if (TypedArrayPrototypeGetByteLength(chunk) === bufByteLength) {
229+
if (
230+
!isSharedArrayBuffer(buf) &&
231+
TypedArrayPrototypeGetByteLength(chunk) ===
232+
ArrayBufferPrototypeGetByteLength(buf)
233+
) {
229234
return chunk;
230235
}
231236
}
232-
return new Uint8Array(chunk);
237+
return copyBytes(chunk);
233238
}
234239
// Multiple chunks: concatenate
235240
let totalByteLength = 0;

test/parallel/test-stream-iter-sharedarraybuffer.js

Lines changed: 4 additions & 2 deletions

0 commit comments

Comments
 (0)