From 41c00f52cb254fa14ca3d507e4baad04b2e80fe9 Mon Sep 17 00:00:00 2001 From: ShuaixinHuang <1836656514@qq.com> Date: Thu, 19 Nov 2026 19:17:19 +0800 Subject: [PATCH] perf(output): avoid encoding UTF-8 excerpts that fit (#12243) --- src/domain/utf8HeadExcerpt.test.ts | 5 +++++ src/domain/utf8HeadExcerpt.ts | 13 ++++++++++--- 2 files changed, 15 insertions(+), 3 deletions(-) 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)),