* Truncate a string to at most `maxBytes` UTF-8 bytes WITHOUT splitting a * multi-byte code point. Naive `Buffer.subarray(...).toString("utf8")` * replaces any partial codepoint at the cut with U+FFFD (3 bytes), which * paradoxically pushes the output OVER the requested budget when the cut * hap
(input: string, maxBytes: number)
| 189 | * the output past `maxBytes`. |
| 190 | */ |
| 191 | function truncateToByteBudget(input: string, maxBytes: number): string { |
| 192 | if (maxBytes <= 0) return ""; |
| 193 | const buf = Buffer.from(input, "utf8"); |
| 194 | if (buf.length <= maxBytes) return input; |
| 195 | let end = maxBytes; |
| 196 | // Walk back to the nearest UTF-8 codepoint boundary. UTF-8 continuation |
| 197 | // bytes are 10xxxxxx; start bytes are 0xxxxxxx or 11xxxxxx. |
| 198 | while (end > 0 && (buf[end] & 0b1100_0000) === 0b1000_0000) { |
| 199 | end -= 1; |
| 200 | } |
| 201 | return buf.subarray(0, end).toString("utf8"); |
| 202 | } |
no outgoing calls
no test coverage detected