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(ext/web/encoding): avoid copy in decode #16364

Merged
merged 2 commits into from
Oct 23, 2022
Merged
Changes from all 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
17 changes: 6 additions & 11 deletions ext/web/08_text_encoding.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
StringPrototypeCharCodeAt,
StringPrototypeSlice,
TypedArrayPrototypeSubarray,
TypedArrayPrototypeSlice,
Uint8Array,
Uint32Array,
} = window.__bootstrap.primordials;
Expand Down Expand Up @@ -404,27 +403,23 @@
*/
function decode(bytes, encoding) {
const BOMEncoding = BOMSniff(bytes);
let start = 0;
if (BOMEncoding !== null) {
encoding = BOMEncoding;
if (BOMEncoding === "UTF-8") start = 3;
else start = 2;
const start = BOMEncoding === "UTF-8" ? 3 : 2;
bytes = TypedArrayPrototypeSubarray(bytes, start);
}
return new TextDecoder(encoding).decode(
TypedArrayPrototypeSlice(bytes, start),
);
return new TextDecoder(encoding).decode(bytes);
}

/**
* @param {Uint8Array} bytes
*/
function BOMSniff(bytes) {
const BOM = TypedArrayPrototypeSubarray(bytes, 0, 3);
if (BOM[0] === 0xEF && BOM[1] === 0xBB && BOM[2] === 0xBF) {
if (bytes[0] === 0xEF && bytes[1] === 0xBB && bytes[2] === 0xBF) {
return "UTF-8";
}
if (BOM[0] === 0xFE && BOM[1] === 0xFF) return "UTF-16BE";
if (BOM[0] === 0xFF && BOM[1] === 0xFE) return "UTF-16LE";
if (bytes[0] === 0xFE && bytes[1] === 0xFF) return "UTF-16BE";
if (bytes[0] === 0xFF && bytes[1] === 0xFE) return "UTF-16LE";
return null;
}

Expand Down