Skip to content

Commit

Permalink
stream: add fast path for utf8
Browse files Browse the repository at this point in the history
PR-URL: #45483
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Filip Skokan <[email protected]>
  • Loading branch information
anonrig authored and danielleadams committed Jan 3, 2023
1 parent 9f1e5b6 commit d2998b6
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions lib/internal/webstreams/adapters.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ const {
Uint8Array,
} = primordials;

const { TextEncoder } = require('internal/encoding');

const {
ReadableStream,
isReadableStream,
Expand Down Expand Up @@ -54,6 +56,7 @@ const {
const {
createDeferredPromise,
kEmptyObject,
normalizeEncoding,
} = require('internal/util');

const {
Expand All @@ -73,6 +76,8 @@ const finished = require('internal/streams/end-of-stream');

const { UV_EOF } = internalBinding('uv');

const encoder = new TextEncoder();

/**
* @typedef {import('../../stream').Writable} Writable
* @typedef {import('../../stream').Readable} Readable
Expand Down Expand Up @@ -255,11 +260,17 @@ function newStreamWritableFromWritableStream(writableStream, options = kEmptyObj

write(chunk, encoding, callback) {
if (typeof chunk === 'string' && decodeStrings && !objectMode) {
chunk = Buffer.from(chunk, encoding);
chunk = new Uint8Array(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength);
const enc = normalizeEncoding(encoding);

if (enc === 'utf8') {
chunk = encoder.encode(chunk);
} else {
chunk = Buffer.from(chunk, encoding);
chunk = new Uint8Array(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength);
}
}

function done(error) {
Expand Down Expand Up @@ -674,11 +685,17 @@ function newStreamDuplexFromReadableWritablePair(pair = kEmptyObject, options =

write(chunk, encoding, callback) {
if (typeof chunk === 'string' && decodeStrings && !objectMode) {
chunk = Buffer.from(chunk, encoding);
chunk = new Uint8Array(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength);
const enc = normalizeEncoding(encoding);

if (enc === 'utf8') {
chunk = encoder.encode(chunk);
} else {
chunk = Buffer.from(chunk, encoding);
chunk = new Uint8Array(
chunk.buffer,
chunk.byteOffset,
chunk.byteLength);
}
}

function done(error) {
Expand Down

0 comments on commit d2998b6

Please sign in to comment.