Expand description
Truncating a string for display without splitting a character.
&s[..n] panics when n lands inside a multi-byte character, and s.len()
is bytes rather than characters — so the obvious spelling of “shorten this
for a log line” is a panic waiting for its first non-ASCII input. That is
not hypothetical: InferenceConfig::extract_client_sampling renders a
rejected client value into a log line, and a request body carrying
{"temperature": "ααααα…"} reached &s[..40] mid-character and took the
request task down with it.
Two call sites wanted the same thing and only one of them got it right, so the right answer lives here once rather than being re-derived per caller.
§Byte budget, not character count
Both functions take max_bytes and cut at or below it. A log line’s
constraint is how much room it has, and a character budget cannot answer
that — 40 characters is 40 bytes of ASCII and 160 bytes of emoji. The cut
then moves down to the nearest character boundary, so the result is
always valid UTF-8 and never longer than asked for.
Functions§
- truncate_
at_ 🔒char_ boundary - Shorten
sto at mostmax_bytes, cutting at a character boundary. - truncate_
with_ 🔒ellipsis truncate_at_char_boundary, with an…marking what was cut.