Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

stream: use Buffer.from when constructor is a Buffer #49250

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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
7 changes: 7 additions & 0 deletions lib/internal/webstreams/readablestream.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,8 @@ const {
writableStreamDefaultWriterWrite,
} = require('internal/webstreams/writablestream');

const { Buffer } = require('buffer');

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

const kCancel = Symbol('kCancel');
Expand Down Expand Up @@ -1904,6 +1906,11 @@ function readableByteStreamControllerConvertPullIntoDescriptor(desc) {
throw new ERR_INVALID_STATE.RangeError('The buffer size is invalid');
assert(!(bytesFilled % elementSize));
const transferredBuffer = transferArrayBuffer(buffer);

if (ctor === Buffer) {
return Buffer.from(transferredBuffer, byteOffset, bytesFilled / elementSize);
}

return new ctor(transferredBuffer, byteOffset, bytesFilled / elementSize);
}

Expand Down
62 changes: 62 additions & 0 deletions test/parallel/test-whatwg-readablebytestreambyob.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
'use strict';

const common = require('../common');

const {
open,
} = require('fs/promises');

const {
Buffer,
} = require('buffer');

class Source {
async start(controller) {
this.file = await open(__filename);
this.controller = controller;
}

async pull(controller) {
const byobRequest = controller.byobRequest;
const view = byobRequest.view;

const {
bytesRead,
} = await this.file.read({
buffer: view,
offset: view.byteOffset,
length: view.byteLength
});

if (bytesRead === 0) {
await this.file.close();
this.controller.close();
}

byobRequest.respond(bytesRead);
}

get type() { return 'bytes'; }

get autoAllocateChunkSize() { return 1024; }
}

(async () => {
KhafraDev marked this conversation as resolved.
Show resolved Hide resolved
const source = new Source();
const stream = new ReadableStream(source);

const { emitWarning } = process;

process.emitWarning = common.mustNotCall();

try {
const reader = stream.getReader({ mode: 'byob' });

let result;
do {
result = await reader.read(Buffer.alloc(100));
} while (!result.done);
} finally {
process.emitWarning = emitWarning;
}
})();
KhafraDev marked this conversation as resolved.
Show resolved Hide resolved