Skip to content

Commit 16dddd2

Browse files
committed
stream: support typed arrays
1 parent 60f09c6 commit 16dddd2

File tree

6 files changed

+162
-37
lines changed

6 files changed

+162
-37
lines changed

doc/api/stream.md

+39-26
Original file line numberDiff line numberDiff line change
@@ -283,10 +283,10 @@ The `finished` API also provides a [callback version][stream-finished].
283283
### Object mode
284284

285285
All streams created by Node.js APIs operate exclusively on strings and `Buffer`
286-
(or `Uint8Array`) objects. It is possible, however, for stream implementations
287-
to work with other types of JavaScript values (with the exception of `null`,
288-
which serves a special purpose within streams). Such streams are considered to
289-
operate in "object mode".
286+
(or {TypedArray} and {DataView}) objects. It is possible, however, for stream
287+
implementations to work with other types of JavaScript values (with the
288+
exception of `null`, which serves a special purpose within streams).
289+
Such streams are considered to operate in "object mode".
290290

291291
Stream instances are switched into object mode using the `objectMode` option
292292
when the stream is created. Attempting to switch an existing stream into
@@ -712,6 +712,9 @@ console.log(myStream.destroyed); // true
712712
<!-- YAML
713713
added: v0.9.4
714714
changes:
715+
- version: REPLACEME
716+
pr-url: https://github.com/nodejs/node/pull/51866
717+
description: The `chunk` argument can now be a `TypedArray` or `DataView` instance.
715718
- version: v15.0.0
716719
pr-url: https://github.com/nodejs/node/pull/34101
717720
description: The `callback` is invoked before 'finish' or on error.
@@ -726,10 +729,10 @@ changes:
726729
description: The `chunk` argument can now be a `Uint8Array` instance.
727730
-->
728731

729-
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
730-
not operating in object mode, `chunk` must be a string, `Buffer` or
731-
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
732-
other than `null`.
732+
* `chunk` {string|Buffer|TypedArray|DataView|any} Optional data to write. For
733+
streams not operating in object mode, `chunk` must be a {string}, {Buffer},
734+
{TypedArray} or {DataView}. For object mode streams, `chunk` may be any
735+
JavaScript value other than `null`.
733736
* `encoding` {string} The encoding if `chunk` is a string
734737
* `callback` {Function} Callback for when the stream is finished.
735738
* Returns: {this}
@@ -926,6 +929,9 @@ Getter for the property `objectMode` of a given `Writable` stream.
926929
<!-- YAML
927930
added: v0.9.4
928931
changes:
932+
- version: REPLACEME
933+
pr-url: https://github.com/nodejs/node/pull/51866
934+
description: The `chunk` argument can now be a `TypedArray` or `DataView` instance.
929935
- version: v8.0.0
930936
pr-url: https://github.com/nodejs/node/pull/11608
931937
description: The `chunk` argument can now be a `Uint8Array` instance.
@@ -935,10 +941,10 @@ changes:
935941
considered invalid now, even in object mode.
936942
-->
937943

938-
* `chunk` {string|Buffer|Uint8Array|any} Optional data to write. For streams
939-
not operating in object mode, `chunk` must be a string, `Buffer` or
940-
`Uint8Array`. For object mode streams, `chunk` may be any JavaScript value
941-
other than `null`.
944+
* `chunk` {string|Buffer|TypedArray|DataView|any} Optional data to write. For
945+
streams not operating in object mode, `chunk` must be a {string}, {Buffer},
946+
{TypedArray} or {DataView}. For object mode streams, `chunk` may be any
947+
JavaScript value other than `null`.
942948
* `encoding` {string|null} The encoding, if `chunk` is a string. **Default:** `'utf8'`
943949
* `callback` {Function} Callback for when this chunk of data is flushed.
944950
* Returns: {boolean} `false` if the stream wishes for the calling code to
@@ -1763,15 +1769,18 @@ setTimeout(() => {
17631769
<!-- YAML
17641770
added: v0.9.11
17651771
changes:
1772+
- version: REPLACEME
1773+
pr-url: https://github.com/nodejs/node/pull/51866
1774+
description: The `chunk` argument can now be a `TypedArray` or `DataView` instance.
17661775
- version: v8.0.0
17671776
pr-url: https://github.com/nodejs/node/pull/11608
17681777
description: The `chunk` argument can now be a `Uint8Array` instance.
17691778
-->
17701779

1771-
* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to unshift onto the
1772-
read queue. For streams not operating in object mode, `chunk` must be a
1773-
string, `Buffer`, `Uint8Array`, or `null`. For object mode streams, `chunk`
1774-
may be any JavaScript value.
1780+
* `chunk` {Buffer|TypedArray|DataView|string|null|any} Chunk of data to unshift
1781+
onto the read queue. For streams not operating in object mode, `chunk` must
1782+
be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`.
1783+
For object mode streams, `chunk` may be any JavaScript value.
17751784
* `encoding` {string} Encoding of string chunks. Must be a valid
17761785
`Buffer` encoding, such as `'utf8'` or `'ascii'`.
17771786

@@ -3512,8 +3521,8 @@ changes:
35123521
**Default:** `'utf8'`.
35133522
* `objectMode` {boolean} Whether or not the
35143523
[`stream.write(anyObj)`][stream-write] is a valid operation. When set,
3515-
it becomes possible to write JavaScript values other than string,
3516-
`Buffer` or `Uint8Array` if supported by the stream implementation.
3524+
it becomes possible to write JavaScript values other than string, {Buffer},
3525+
{TypedArray} or {DataView} if supported by the stream implementation.
35173526
**Default:** `false`.
35183527
* `emitClose` {boolean} Whether or not the stream should emit `'close'`
35193528
after it has been destroyed. **Default:** `true`.
@@ -4062,22 +4071,25 @@ It can be overridden by child classes but it **must not** be called directly.
40624071

40634072
<!-- YAML
40644073
changes:
4074+
- version: REPLACEME
4075+
pr-url: https://github.com/nodejs/node/pull/51866
4076+
description: The `chunk` argument can now be a `TypedArray` or `DataView` instance.
40654077
- version: v8.0.0
40664078
pr-url: https://github.com/nodejs/node/pull/11608
40674079
description: The `chunk` argument can now be a `Uint8Array` instance.
40684080
-->
40694081

4070-
* `chunk` {Buffer|Uint8Array|string|null|any} Chunk of data to push into the
4071-
read queue. For streams not operating in object mode, `chunk` must be a
4072-
string, `Buffer` or `Uint8Array`. For object mode streams, `chunk` may be
4073-
any JavaScript value.
4082+
* `chunk` {Buffer|TypedArray|DataView|string|null|any} Chunk of data to push
4083+
into the read queue. For streams not operating in object mode, `chunk` must
4084+
be a {string}, {Buffer}, {TypedArray} or {DataView}. For object mode streams,
4085+
`chunk` may be any JavaScript value.
40744086
* `encoding` {string} Encoding of string chunks. Must be a valid
40754087
`Buffer` encoding, such as `'utf8'` or `'ascii'`.
40764088
* Returns: {boolean} `true` if additional chunks of data may continue to be
40774089
pushed; `false` otherwise.
40784090

4079-
When `chunk` is a `Buffer`, `Uint8Array`, or `string`, the `chunk` of data will
4080-
be added to the internal queue for users of the stream to consume.
4091+
When `chunk` is a {Buffer}, {TypedArray}, {DataView} or {string}, the `chunk`
4092+
of data will be added to the internal queue for users of the stream to consume.
40814093
Passing `chunk` as `null` signals the end of the stream (EOF), after which no
40824094
more data can be written.
40834095

@@ -4752,8 +4764,9 @@ situations within Node.js where this is done, particularly in the
47524764

47534765
Use of `readable.push('')` is not recommended.
47544766

4755-
Pushing a zero-byte string, `Buffer`, or `Uint8Array` to a stream that is not in
4756-
object mode has an interesting side effect. Because it _is_ a call to
4767+
Pushing a zero-byte {string}, {Buffer}, {TypedArray} or {DataView} to a stream
4768+
that is not in object mode has an interesting side effect.
4769+
Because it _is_ a call to
47574770
[`readable.push()`][stream-push], the call will end the reading process.
47584771
However, because the argument is an empty string, no data is added to the
47594772
readable buffer so there is nothing for a user to consume.

lib/internal/streams/readable.js

+9-6
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ const {
3636
SymbolAsyncIterator,
3737
SymbolSpecies,
3838
TypedArrayPrototypeSet,
39+
Uint8Array,
3940
} = primordials;
4041

4142
module.exports = Readable;
@@ -420,11 +421,12 @@ function readableAddChunkUnshiftByteMode(stream, state, chunk, encoding) {
420421
chunk = Buffer.from(chunk, encoding);
421422
}
422423
}
423-
} else if (Stream._isUint8Array(chunk)) {
424-
chunk = Stream._uint8ArrayToBuffer(chunk);
424+
} else if (Stream._isArrayBufferView(chunk)) {
425+
const array = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
426+
chunk = Stream._uint8ArrayToBuffer(array);
425427
} else if (chunk !== undefined && !(chunk instanceof Buffer)) {
426428
errorOrDestroy(stream, new ERR_INVALID_ARG_TYPE(
427-
'chunk', ['string', 'Buffer', 'Uint8Array'], chunk));
429+
'chunk', ['string', 'Buffer', 'TypedArray', 'BufferView'], chunk));
428430
return false;
429431
}
430432

@@ -473,12 +475,13 @@ function readableAddChunkPushByteMode(stream, state, chunk, encoding) {
473475
}
474476
} else if (chunk instanceof Buffer) {
475477
encoding = '';
476-
} else if (Stream._isUint8Array(chunk)) {
477-
chunk = Stream._uint8ArrayToBuffer(chunk);
478+
} else if (Stream._isArrayBufferView(chunk)) {
479+
const array = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
480+
chunk = Stream._uint8ArrayToBuffer(array);
478481
encoding = '';
479482
} else if (chunk !== undefined) {
480483
errorOrDestroy(stream, new ERR_INVALID_ARG_TYPE(
481-
'chunk', ['string', 'Buffer', 'Uint8Array'], chunk));
484+
'chunk', ['string', 'Buffer', 'TypedArray', 'BufferView'], chunk));
482485
return false;
483486
}
484487

lib/internal/streams/writable.js

+5-3
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ const {
3535
StringPrototypeToLowerCase,
3636
Symbol,
3737
SymbolHasInstance,
38+
Uint8Array,
3839
} = primordials;
3940

4041
module.exports = Writable;
@@ -467,12 +468,13 @@ function _write(stream, chunk, encoding, cb) {
467468
}
468469
} else if (chunk instanceof Buffer) {
469470
encoding = 'buffer';
470-
} else if (Stream._isUint8Array(chunk)) {
471-
chunk = Stream._uint8ArrayToBuffer(chunk);
471+
} else if (Stream._isArrayBufferView(chunk)) {
472+
const array = new Uint8Array(chunk.buffer, chunk.byteOffset, chunk.byteLength);
473+
chunk = Stream._uint8ArrayToBuffer(array);
472474
encoding = 'buffer';
473475
} else {
474476
throw new ERR_INVALID_ARG_TYPE(
475-
'chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
477+
'chunk', ['string', 'Buffer', 'TypedArray', 'BufferView'], chunk);
476478
}
477479
}
478480

lib/stream.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@ const internalBuffer = require('internal/buffer');
5050

5151
const promises = require('stream/promises');
5252
const utils = require('internal/streams/utils');
53+
const { isArrayBufferView, isUint8Array } = require('internal/util/types');
5354

5455
const Stream = module.exports = require('internal/streams/legacy').Stream;
5556

@@ -137,7 +138,8 @@ ObjectDefineProperty(eos, customPromisify, {
137138
// Backwards-compat with node 0.4.x
138139
Stream.Stream = Stream;
139140

140-
Stream._isUint8Array = require('internal/util/types').isUint8Array;
141+
Stream._isArrayBufferView = isArrayBufferView;
142+
Stream._isUint8Array = isUint8Array;
141143
Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) {
142144
return new internalBuffer.FastBuffer(chunk.buffer,
143145
chunk.byteOffset,

test/parallel/test-net-write-arguments.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,6 @@ assert.throws(() => {
3434
code: 'ERR_INVALID_ARG_TYPE',
3535
name: 'TypeError',
3636
message: 'The "chunk" argument must be of type string or an instance of ' +
37-
`Buffer or Uint8Array.${common.invalidArgTypeHelper(value)}`
37+
`Buffer, TypedArray, or BufferView.${common.invalidArgTypeHelper(value)}`
3838
});
3939
});
+105
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
'use strict';
2+
const common = require('../common');
3+
const assert = require('assert');
4+
5+
const { Readable, Writable } = require('stream');
6+
7+
const buffer = Buffer.from('ABCD');
8+
const views = common.getArrayBufferViews(buffer);
9+
10+
{
11+
// Simple Writable test.
12+
let n = 0;
13+
const writable = new Writable({
14+
write: common.mustCall((chunk, encoding, cb) => {
15+
assert(chunk instanceof Buffer);
16+
assert(ArrayBuffer.isView(chunk));
17+
assert.deepStrictEqual(common.getBufferSources(chunk)[n], views[n]);
18+
n++;
19+
cb();
20+
}, views.length),
21+
});
22+
23+
views.forEach((msg) => writable.write(msg));
24+
writable.end();
25+
}
26+
27+
{
28+
// Writable test with object mode True.
29+
let n = 0;
30+
const writable = new Writable({
31+
objectMode: true,
32+
write: common.mustCall((chunk, encoding, cb) => {
33+
assert(!(chunk instanceof Buffer));
34+
assert(ArrayBuffer.isView(chunk));
35+
assert.deepStrictEqual(common.getBufferSources(chunk)[n], views[n]);
36+
n++;
37+
cb();
38+
}, views.length),
39+
});
40+
41+
views.forEach((msg) => writable.write(msg));
42+
writable.end();
43+
}
44+
45+
46+
{
47+
// Writable test, multiple writes carried out via writev.
48+
let n = 0;
49+
let callback;
50+
const writable = new Writable({
51+
write: common.mustCall((chunk, encoding, cb) => {
52+
assert(chunk instanceof Buffer);
53+
assert(ArrayBuffer.isView(chunk));
54+
assert.deepStrictEqual(common.getBufferSources(chunk)[n], views[n]);
55+
n++;
56+
callback = cb;
57+
}),
58+
59+
writev: common.mustCall((chunks, cb) => {
60+
assert.strictEqual(chunks.length, views.length);
61+
let res = '';
62+
for (const chunk of chunks) {
63+
assert.strictEqual(chunk.encoding, 'buffer');
64+
res += chunk.chunk;
65+
}
66+
assert.strictEqual(res, 'ABCD'.repeat(9));
67+
}),
68+
69+
});
70+
views.forEach((msg) => writable.write(msg));
71+
writable.end(views[0]);
72+
callback();
73+
}
74+
75+
76+
{
77+
// Simple Readable test.
78+
const readable = new Readable({
79+
read() {}
80+
});
81+
82+
readable.push(views[1]);
83+
readable.push(views[2]);
84+
readable.unshift(views[0]);
85+
86+
const buf = readable.read();
87+
assert(buf instanceof Buffer);
88+
assert.deepStrictEqual([...buf], [...views[0], ...views[1], ...views[2]]);
89+
}
90+
91+
{
92+
// Readable test, setEncoding.
93+
const readable = new Readable({
94+
read() {}
95+
});
96+
97+
readable.setEncoding('utf8');
98+
99+
readable.push(views[1]);
100+
readable.push(views[2]);
101+
readable.unshift(views[0]);
102+
103+
const out = readable.read();
104+
assert.strictEqual(out, 'ABCD'.repeat(3));
105+
}

0 commit comments

Comments
 (0)