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 <jasnell@gmail.com>
Reviewed-By: Filip Skokan <panva.ip@gmail.com>
  • Loading branch information
anonrig authored and ruyadorno committed Nov 21, 2022
1 parent b491504 commit 8d96e2c
Showing 1 changed file with 27 additions and 10 deletions.
37 changes: 27 additions & 10 deletions lib/internal/webstreams/adapters.js
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 8d96e2c

Please sign in to comment.