Skip to content

Commit 0969e19

Browse files
committed
fix: keep a leading U+FEFF when decoding long strings
1 parent 6d4b666 commit 0969e19

2 files changed

Lines changed: 19 additions & 1 deletion

File tree

‎src/utils/utf8.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,7 +157,8 @@ export function utf8DecodeJs(bytes: Uint8Array, inputOffset: number, byteLength:
157157
return result;
158158
}
159159

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

162163
// This threshold should be determined by benchmarking, which might vary in engines and input data.
163164
// Run `npx ts-node benchmark/decode-string.ts` for details.

‎test/utf8-bom.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import assert from "assert";
2+
import { encode, decode } from "../src/index.ts";
3+
4+
describe("leading U+FEFF", () => {
5+
// strings longer than 200 bytes are decoded by `TextDecoder`, shorter ones by `utf8DecodeJs()`
6+
for (const length of [10, 300]) {
7+
it(`keeps it in a string of ${length} characters`, () => {
8+
const string = "\uFEFF" + "a".repeat(length);
9+
assert.strictEqual(decode(encode(string)), string);
10+
});
11+
12+
it(`keeps it in a map key of ${length} characters`, () => {
13+
const key = "\uFEFF" + "a".repeat(length);
14+
assert.deepStrictEqual(Object.keys(decode(encode({ [key]: 1 })) as object), [key]);
15+
});
16+
}
17+
});

0 commit comments

Comments
 (0)