Skip to content
Open
Show file tree
Hide file tree
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
3 changes: 2 additions & 1 deletion src/utils/utf8.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,8 @@ export function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength:
return result;
}

const sharedTextDecoder = new TextDecoder();
// `ignoreBOM` keeps a leading U+FEFF as part of the string, as `utf8DecodeJs()` does.
const sharedTextDecoder = new TextDecoder("utf-8", { ignoreBOM: true });

// This threshold should be determined by benchmarking, which might vary in engines and input data.
// Run `npx ts-node benchmark/decode-string.ts` for details.
Expand Down
17 changes: 17 additions & 0 deletions test/utf8-bom.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import assert from "assert";
import { encode, decode } from "../src/index.ts";

describe("leading U+FEFF", () => {
// strings longer than 200 bytes are decoded by `TextDecoder`, shorter ones by `utf8DecodeJs()`
for (const length of [10, 300]) {
it(`keeps it in a string of ${length} characters`, () => {
const string = "\uFEFF" + "a".repeat(length);
assert.strictEqual(decode(encode(string)), string);
});

it(`keeps it in a map key of ${length} characters`, () => {
const key = "\uFEFF" + "a".repeat(length);
assert.deepStrictEqual(Object.keys(decode(encode({ [key]: 1 })) as object), [key]);
});
}
});