diff --git a/src/domain/utf8HeadExcerpt.test.ts b/src/domain/utf8HeadExcerpt.test.ts index 4fc837c6ff..a5e4a3a21b 100644 --- a/src/domain/utf8HeadExcerpt.test.ts +++ b/src/domain/utf8HeadExcerpt.test.ts @@ -8,6 +8,11 @@ it("keeps text within the budget unchanged", () => { bytes: 3, truncated: false, }); + expect(utf8HeadExcerpt("𐐷\uD800", 9)).toEqual({ + text: "𐐷\uD800", + bytes: 7, + truncated: false, + }); expect(utf8HeadExcerpt("", 0)).toEqual({ text: "", bytes: 0, diff --git a/src/domain/utf8HeadExcerpt.ts b/src/domain/utf8HeadExcerpt.ts index 68e8b6b8ce..3db70d2431 100644 --- a/src/domain/utf8HeadExcerpt.ts +++ b/src/domain/utf8HeadExcerpt.ts @@ -16,11 +16,18 @@ export const utf8HeadExcerpt = ( } => { if (maximumBytes <= 0) return { text: excerptText(""), bytes: 0, truncated: text.length > 0 }; - // A UTF-16 code unit encodes to at most three UTF-8 bytes, and encodeInto - // stops before the first character that does not fit. + // Every UTF-16 code unit needs at most three UTF-8 bytes. If the + // budget fits that worst case, count bytes without encoding the text. + if (text.length * 3 <= maximumBytes) + return { + text: excerptText(text), + bytes: Buffer.byteLength(text, "utf8"), + truncated: false, + }; + // encodeInto stops before the first character that does not fit. const { read, written } = new TextEncoder().encodeInto( text, - new Uint8Array(Math.min(maximumBytes, text.length * 3)), + new Uint8Array(maximumBytes), ); return { text: excerptText(text.slice(0, read)),