diff --git a/src/domain/canonicalJsonDigestSteps.ts b/src/domain/canonicalJsonDigestSteps.ts index 2b7183289d9..b996b9068dc 100644 --- a/src/domain/canonicalJsonDigestSteps.ts +++ b/src/domain/canonicalJsonDigestSteps.ts @@ -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); diff --git a/src/domain/jsonSerialization.ts b/src/domain/jsonSerialization.ts index 0feb8a772dd..a849f405c31 100644 --- a/src/domain/jsonSerialization.ts +++ b/src/domain/jsonSerialization.ts @@ -172,25 +172,21 @@ export function* bufferedJsonParts(parts: Iterable): Generator { if (buffer !== "") yield buffer; } -function* encodeString(value: string): Generator { - 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 { 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 ? ": " : ":"; }