refactor(json): share surrogate-safe string chunk boundaries (#16884)

This commit is contained in:
Vincent Koc authored and GitHub committed 2026-12-05 09:09:04 +08:00
1 parent 00295795de
commit 0026fbfe94
2 files changed
+17 -30

No files matched your search

+2 -11
View File
@@ -1,6 +1,7 @@
import { createHash } from "node:crypto";
import { CanonicalDigestError } from "./canonicalDigest.js";
import type { JsonValue } from "./jsonValue.js";
import { jsonStringChunkEnd } from "./jsonSerialization.js";
type DigestFrame =
| { readonly kind: "separator" }
@@ -57,17 +58,7 @@ export function* canonicalJsonDigestSteps(
emit('"');
continue;
}
let end = Math.min(frame.index + 8192, frame.value.length);
const last = frame.value.charCodeAt(end - 1);
const next = frame.value.charCodeAt(end);
if (
end < frame.value.length &&
last >= 0xd800 &&
last <= 0xdbff &&
next >= 0xdc00 &&
next <= 0xdfff
)
end -= 1;
const end = jsonStringChunkEnd(frame.value, frame.index);
emit(JSON.stringify(frame.value.slice(frame.index, end)).slice(1, -1));
frame.index = end;
stack.push(frame);
+15 -19
View File
@@ -172,25 +172,21 @@ export function* bufferedJsonParts(parts: Iterable<string>): Generator<string> {
if (buffer !== "") yield buffer;
}
function* encodeString(value: string): Generator<string> {
if (value.length <= 8192) {
yield JSON.stringify(value);
return;
}
/** Keep a surrogate pair in the same JSON.stringify and UTF-8 write. */
export const jsonStringChunkEnd = (value: string, start: number): number => {
const end = Math.min(start + 8192, value.length);
if (end === value.length) return end;
const last = value.charCodeAt(end - 1);
const next = value.charCodeAt(end);
return last >= 0xd800 && last <= 0xdbff && next >= 0xdc00 && next <= 0xdfff
? end - 1
: end;
};
function* encodeLongString(value: string): Generator<string> {
yield '"';
for (let start = 0; start < value.length;) {
let end = Math.min(start + 8192, value.length);
const last = value.charCodeAt(end - 1);
const next = value.charCodeAt(end);
// Keep a surrogate pair in the same JSON.stringify and UTF-8 write.
if (
end < value.length &&
last >= 0xd800 &&
last <= 0xdbff &&
next >= 0xdc00 &&
next <= 0xdfff
)
end -= 1;
const end = jsonStringChunkEnd(value, start);
yield JSON.stringify(value.slice(start, end)).slice(1, -1);
start = end;
}
@@ -311,7 +307,7 @@ function* encodeValue(
// A long string is split into surrogate-safe parts of its own.
if (buffer !== "") yield buffer;
buffer = "";
yield* encodeString(pending);
yield* encodeLongString(pending);
} else {
const frame = openContainer(
pending,
@@ -360,7 +356,7 @@ function* encodeValue(
else {
if (buffer !== "") yield buffer;
buffer = "";
yield* encodeString(frame.memberKey);
yield* encodeLongString(frame.memberKey);
}
buffer += pretty ? ": " : ":";
}