Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions benchmark/streams/consumers.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use strict';

const common = require('../common.js');
const { Readable } = require('node:stream');
const consumers = require('node:stream/consumers');

const bench = common.createBenchmark(main, {
method: ['arrayBuffer', 'buffer', 'bytes', 'blob'],
type: ['buffer', 'string'],
chunks: [4, 32],
n: [2e3],
});

async function main({ n, method, type, chunks }) {
const consume = consumers[method];
const chunk = type === 'buffer' ?
Buffer.alloc(1024, 65) :
'a'.repeat(1024);
const data = Array.from({ length: chunks }, () => chunk);

// Warmup
for (let i = 0; i < 100; i++) {
await consume(Readable.from(data));
}

let total = 0;
bench.start();
for (let i = 0; i < n; i++) {
const res = await consume(Readable.from(data));
total += res.byteLength ?? res.size;
}
bench.end(n);

if (total === 0) {
throw new Error('Unexpected empty result');
}
}
63 changes: 61 additions & 2 deletions lib/stream/consumers.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,26 @@
'use strict';

const {
ArrayBuffer,
ArrayBufferPrototypeGetResizable,
JSONParse,
TypedArrayPrototypeGetBuffer,
TypedArrayPrototypeGetByteLength,
TypedArrayPrototypeSet,
Uint8Array,
} = primordials;

const {
createUnsafeArrayBuffer,
kMaxLength,
} = internalBinding('buffer');

const assert = require('internal/assert');

const {
ERR_BUFFER_TOO_LARGE,
} = require('internal/errors').codes;

const {
TextDecoder,
} = require('internal/encoding');
Expand All @@ -13,6 +29,11 @@ const {
Blob,
} = require('internal/blob');

const {
isArrayBuffer,
isUint8Array,
} = require('internal/util/types');

const {
Buffer,
} = require('buffer');
Expand All @@ -34,13 +55,51 @@ async function blob(stream) {
return new Blob(chunks);
}

/**
* @param {any[]} chunks
* @returns {ArrayBuffer | null}
*/
function concatUint8Arrays(chunks) {
let totalLength = 0;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
if (!isUint8Array(chunk))
return null;
const backing = TypedArrayPrototypeGetBuffer(chunk);
if (!isArrayBuffer(backing) || ArrayBufferPrototypeGetResizable(backing))
return null;
totalLength += TypedArrayPrototypeGetByteLength(chunk);
}

if (totalLength === 0)
return new ArrayBuffer(0);
if (totalLength > kMaxLength)
throw new ERR_BUFFER_TOO_LARGE(kMaxLength);

const result = createUnsafeArrayBuffer(totalLength);
const view = new Uint8Array(result);
let offset = 0;
for (let i = 0; i < chunks.length; i++) {
const chunk = chunks[i];
const byteLength = TypedArrayPrototypeGetByteLength(chunk);
if (byteLength !== 0) {
TypedArrayPrototypeSet(view, chunk, offset);
offset += byteLength;
}
}
assert(offset === totalLength);
return result;
}

/**
* @param {AsyncIterable|ReadableStream|Readable} stream
* @returns {Promise<ArrayBuffer>}
*/
async function arrayBuffer(stream) {
const ret = await blob(stream);
return ret.arrayBuffer();
const chunks = [];
for await (const chunk of stream)
chunks[chunks.length] = chunk;
return concatUint8Arrays(chunks) ?? new Blob(chunks).arrayBuffer();
}

/**
Expand Down
81 changes: 81 additions & 0 deletions test/parallel/test-stream-consumers.js
Original file line number Diff line number Diff line change
Expand Up @@ -291,3 +291,84 @@ const kArrayBuffer =
writer.close(),
]).then(common.mustCall());
}

{
arrayBuffer(Readable.from([])).then(common.mustCall((ab) => {
assert(ab instanceof ArrayBuffer);
assert.strictEqual(ab.byteLength, 0);
}));
}

{
const a = new Uint8Array([1, 2, 3]);
const b = new Uint8Array([4, 5]);
arrayBuffer(Readable.from([a, new Uint8Array(0), b])).then(common.mustCall((ab) => {
a.fill(0);
b.fill(0);
assert.deepStrictEqual(new Uint8Array(ab), new Uint8Array([1, 2, 3, 4, 5]));
}));
}

{
const detached = new ArrayBuffer(4);
const detachedView = new Uint8Array(detached);
detachedView.set([9, 8, 7, 6]);
detached.transfer();
arrayBuffer(Readable.from([new Uint8Array([1, 2]), detachedView, new Uint8Array([3])]))
.then(common.mustCall((ab) => {
assert.deepStrictEqual(new Uint8Array(ab), new Uint8Array([1, 2, 3]));
}));
}

{
const resizable = new ArrayBuffer(4, { maxByteLength: 16 });
assert.rejects(
arrayBuffer(Readable.from([Buffer.from('a'), new Uint8Array(resizable)])),
{
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: /resizable ArrayBuffer/,
},
).then(common.mustCall());
}

{
const sab = new SharedArrayBuffer(4);
assert.rejects(
arrayBuffer(Readable.from([Buffer.from('a'), new Uint8Array(sab)])),
{
name: 'TypeError',
code: 'ERR_INVALID_ARG_TYPE',
message: /SharedArrayBuffer/,
},
).then(common.mustCall());
}

{
buffer(Readable.from([Buffer.from('hello '), 'world'])).then(common.mustCall((buf) => {
assert.strictEqual(buf.toString(), 'hello world');
}));
}

{
const u16 = new Uint16Array([0x0201]);
const dvBuf = new ArrayBuffer(4);
new Uint8Array(dvBuf).set([10, 20, 30, 40]);
const rawAb = new Uint8Array([50, 60]).buffer;
const clamped = new Uint8ClampedArray([70, 80]);
const mixed = [
Buffer.from([0]),
u16,
new DataView(dvBuf, 1, 2),
rawAb,
clamped,
];
const expected = Buffer.concat([
Buffer.from([0]),
Buffer.from(u16.buffer, u16.byteOffset, u16.byteLength),
Buffer.from([20, 30, 50, 60, 70, 80]),
]);
buffer(Readable.from(mixed)).then(common.mustCall((buf) => {
assert.deepStrictEqual(buf, expected);
}));
}