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

perf: optimize consumeEnd #2510

Merged
merged 12 commits into from
Dec 9, 2023
55 changes: 35 additions & 20 deletions lib/api/readable.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ const assert = require('assert')
const { Readable } = require('stream')
const { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError } = require('../core/errors')
const util = require('../core/util')
const { ReadableStreamFrom, toUSVString } = require('../core/util')
const { ReadableStreamFrom } = require('../core/util')

let Blob

Expand Down Expand Up @@ -267,29 +267,44 @@ function consumeStart (consume) {
}
}

const decoder = new TextDecoder()

/**
* @see https://encoding.spec.whatwg.org/#utf-8-decode
* @param {Buffer} buffer
*/
function utf8DecodeBytes (buffer) {
tsctx marked this conversation as resolved.
Show resolved Hide resolved
if (buffer.length === 0) {
return ''
}
// 1.
// 2.
if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
buffer = buffer.subarray(3)
}
// 3.
const output = decoder.decode(buffer)
// 4.
return output
}

function consumeEnd (consume) {
const { type, body, resolve, stream, length } = consume

try {
if (type === 'text') {
resolve(toUSVString(Buffer.concat(body)))
} else if (type === 'json') {
resolve(JSON.parse(Buffer.concat(body)))
} else if (type === 'arrayBuffer') {
const dst = new Uint8Array(length)

let pos = 0
for (const buf of body) {
dst.set(buf, pos)
pos += buf.byteLength
}

resolve(dst.buffer)
} else if (type === 'blob') {
if (!Blob) {
Blob = require('buffer').Blob
}
resolve(new Blob(body, { type: stream[kContentType] }))
switch (type) {
tsctx marked this conversation as resolved.
Show resolved Hide resolved
case 'text':
resolve(utf8DecodeBytes(Buffer.concat(body, length)))
break
case 'json':
resolve(JSON.parse(utf8DecodeBytes(Buffer.concat(body, length))))
tsctx marked this conversation as resolved.
Show resolved Hide resolved
break
case 'arrayBuffer':
resolve(Buffer.concat(body, length).buffer)
break
case 'blob':
resolve(new (Blob ??= require('buffer').Blob)(body, { type: stream[kContentType] }))
tsctx marked this conversation as resolved.
Show resolved Hide resolved
break
}

consumeFinish(consume)
Expand Down
Loading