From 0969e19d40b2c94c5c0aecbd96fa6e14b7440ace Mon Sep 17 00:00:00 2001 From: Shigma Date: Sun, 29 Nov 2026 20:11:02 +0800 Subject: [PATCH] fix: keep a leading U+FEFF when decoding long strings --- src/utils/utf8.ts | 3 ++- test/utf8-bom.test.ts | 17 +++++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) create mode 100644 test/utf8-bom.test.ts diff --git a/src/utils/utf8.ts b/src/utils/utf8.ts index 1494f70..0e46d21 100644 --- a/src/utils/utf8.ts +++ b/src/utils/utf8.ts @@ -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. diff --git a/test/utf8-bom.test.ts b/test/utf8-bom.test.ts new file mode 100644 index 0000000..5fb6b19 --- /dev/null +++ b/test/utf8-bom.test.ts @@ -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]); + }); + } +});