MCPcopy Create free account
hub / github.com/cortexkit/magic-context / truncateToByteBudget

Function truncateToByteBudget

packages/cli/src/lib/issue-body.ts:191–202  ·  view source on GitHub ↗

* 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)

Source from the content-addressed store, hash-verified

189 * the output past `maxBytes`.
190 */
191function 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}

Callers 1

capBodyToGithubLimitFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected