GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — stream: avoid batch entries for single-chunk pipeTo() writes · nodejs/node@32c3d1e

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • lib/internal/streams/iter
    • pull.js
    • utils.js
  • test/parallel
    • test-stream-iter-resizable-buffers.js
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎lib/internal/streams/iter/pull.js‎

Copy file name to clipboardExpand all lines: lib/internal/streams/iter/pull.js
+23Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ const {
1919
PromiseResolve,
2020
SymbolAsyncIterator,
2121
SymbolIterator,
22+
TypedArrayPrototypeGetByteLength,
2223
Uint8Array,
2324
} = primordials;
2425

@@ -54,6 +55,7 @@ const {
5455
const {
5556
IterResult,
5657
kNullOnceOption,
58+
callWithByteView,
5759
createBatchEntry,
5860
isTransformObject,
5961
parsePullArgs,
@@ -1063,6 +1065,16 @@ function pipeToSync(source, ...args) {
10631065

10641066
try {
10651067
for (const batch of pipeline) {
1068+
// Single chunk, the common case: no batch entry needed.
1069+
if (batch.length === 1) {
1070+
const chunk = batch[0];
1071+
if (callWithByteView(chunk, writer.writeSync, writer) === false) {
1072+
throw new ERR_OUT_OF_RANGE(
1073+
'write', 'within byte budget', 'budget exhausted');
1074+
}
1075+
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
1076+
continue;
1077+
}
10661078
const entry = createBatchEntry(batch);
10671079
if (hasWritevSync && batch.length > 1) {
10681080
const accepted = writer.writevSync(validateBatchEntry(entry));
@@ -1190,6 +1202,17 @@ async function pipeTo(source, ...args) {
11901202
// Returns undefined on sync success, or a Promise when async fallback
11911203
// is required. Callers must check: const p = writeBatch(b); if (p) await p;
11921204
function writeBatch(batch) {
1205+
// Single chunk, the common case: check the view around writeSync()
1206+
// without allocating a batch entry, and create one only to fall back to
1207+
// the async path.
1208+
if (batch.length === 1 && hasWriteSync) {
1209+
const chunk = batch[0];
1210+
if (callWithByteView(chunk, writer.writeSync, writer)) {
1211+
totalBytes += TypedArrayPrototypeGetByteLength(chunk);
1212+
return;
1213+
}
1214+
return writeBatchAsyncFallback(createBatchEntry(batch), 0);
1215+
}
11931216
const entry = createBatchEntry(batch);
11941217
if (hasWritev && batch.length > 1) {
11951218
if (!hasWritevSync ||
Collapse file

‎lib/internal/streams/iter/utils.js‎

Copy file name to clipboardExpand all lines: lib/internal/streams/iter/utils.js
+37Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const {
77
ArrayBufferPrototypeGetResizable,
88
ArrayPrototypePush,
99
ArrayPrototypeSlice,
10+
FunctionPrototypeCall,
1011
ObjectDefineProperty,
1112
ObjectFreeze,
1213
PromiseResolve,
@@ -295,6 +296,41 @@ function validateByteView(snapshot) {
295296
return value;
296297
}
297298

299+
/**
300+
* Call `method` on `receiver` with the byte view `value`, and throw if the
301+
* call resized or detached it, as validateByteView() does for a snapshot
302+
* taken just before the call. Used for single-chunk writes, the common case:
303+
* for views on an ArrayBuffer the snapshot is kept in locals instead of a
304+
* ByteViewSnapshot, so that nothing is allocated per chunk.
305+
* @param {Uint8Array} value
306+
* @param {Function} method
307+
* @param {object} receiver
308+
* @returns {any} The result of the call.
309+
*/
310+
function callWithByteView(value, method, receiver) {
311+
const buffer = TypedArrayPrototypeGetBuffer(value);
312+
if (isSharedArrayBuffer(buffer)) {
313+
const snapshot = snapshotByteView(value);
314+
const result = FunctionPrototypeCall(method, receiver, value);
315+
validateByteView(snapshot);
316+
return result;
317+
}
318+
const bufferByteLength = ArrayBufferPrototypeGetByteLength(buffer);
319+
const byteLength = TypedArrayPrototypeGetByteLength(value);
320+
const byteOffset = TypedArrayPrototypeGetByteOffset(value);
321+
const detached = ArrayBufferPrototypeGetDetached(buffer);
322+
const result = FunctionPrototypeCall(method, receiver, value);
323+
if (TypedArrayPrototypeGetBuffer(value) !== buffer ||
324+
ArrayBufferPrototypeGetByteLength(buffer) !== bufferByteLength ||
325+
TypedArrayPrototypeGetByteLength(value) !== byteLength ||
326+
TypedArrayPrototypeGetByteOffset(value) !== byteOffset ||
327+
ArrayBufferPrototypeGetDetached(buffer) !== detached) {
328+
throw new ERR_INVALID_STATE.TypeError(
329+
'Byte view was resized or detached after being accepted');
330+
}
331+
return result;
332+
}
333+
298334
/**
299335
* Validate an explicit `budget` option. The spec only requires the default
300336
* budget to be at least 16384 bytes; any positive explicit budget is valid.
@@ -602,6 +638,7 @@ module.exports = {
602638
kNullOnceOption,
603639
kPushDefaultBudget,
604640
kResolvedPromise,
641+
callWithByteView,
605642
concatBytes,
606643
convertChunks,
607644
createBatchEntry,
Collapse file

‎test/parallel/test-stream-iter-resizable-buffers.js‎

Copy file name to clipboardExpand all lines: test/parallel/test-stream-iter-resizable-buffers.js
+44Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -167,6 +167,49 @@ async function testPipeRejectsWriterResize() {
167167
);
168168
}
169169

170+
// Single-chunk batches are checked around writeSync() without a snapshot
171+
// object. Detaching or resizing the view in writeSync() must still be
172+
// rejected, for views on ArrayBuffers and on growable SharedArrayBuffers.
173+
async function testPipeRejectsSyncWriteDetachOrResize() {
174+
const cases = [
175+
['detach', () => new ArrayBuffer(2), (buffer) => buffer.transfer()],
176+
['resize', () => new ArrayBuffer(1, { maxByteLength: 2 }),
177+
(buffer) => buffer.resize(2)],
178+
['grow shared', () => new SharedArrayBuffer(1, { maxByteLength: 2 }),
179+
(buffer) => buffer.grow(2)],
180+
];
181+
for (const [, createBuffer, change] of cases) {
182+
const asyncBuffer = createBuffer();
183+
await assert.rejects(pipeTo([new Uint8Array(asyncBuffer)], {
184+
writeSync() {
185+
change(asyncBuffer);
186+
return true;
187+
},
188+
write: common.mustNotCall(),
189+
fail: common.mustCall(),
190+
}), kResizeError);
191+
192+
const syncBuffer = createBuffer();
193+
assert.throws(() => pipeToSync([new Uint8Array(syncBuffer)], {
194+
writeSync() {
195+
change(syncBuffer);
196+
return true;
197+
},
198+
fail: common.mustCall(),
199+
}, { preventClose: true }), kResizeError);
200+
}
201+
202+
// An unchanged view is written; when writeSync() declines it, pipeTo()
203+
// falls back to write() for it.
204+
const chunk = Uint8Array.of(1, 2);
205+
const written = [];
206+
assert.strictEqual(await pipeTo([chunk], {
207+
writeSync: () => false,
208+
write(value) { written.push(value); },
209+
}, { preventClose: true }), 2);
210+
assert.deepStrictEqual(written, [chunk]);
211+
}
212+
170213
async function testConsumersRejectDetachedViews() {
171214
// Views of fixed-length buffers are tracked without a full snapshot; they
172215
// must still be rejected when detached after being accepted.
@@ -205,4 +248,5 @@ Promise.all([
205248
testConsumersRejectResizedViews(),
206249
testConsumersRejectDetachedViews(),
207250
testPipeRejectsWriterResize(),
251+
testPipeRejectsSyncWriteDetachOrResize(),
208252
]).then(common.mustCall());

0 commit comments

Comments
0 (0)
You are visitor 01402775 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.