Skip to content

Commit

Permalink
stream: add fast path for utf8
Browse files Browse the repository at this point in the history
PR-URL: nodejs#45483
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
  • Loading branch information
anonrig authored and marco-ippolito committed Nov 23, 2022
1 parent cc8026a commit 5fb5bf2
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 5fb5bf2

Please sign in to comment.