Add TruncateString to shorten a string without splitting a character #5

Closed
opened 2026-09-05 05:24:41 +02:00 by clawbot · 0 comments
Contributor

Cutting a string with a plain byte slice such as s[:80] will split a
multi-byte character in half and produce invalid text, which shows up as a
replacement character in logs, database columns and terminal output. A short
function that counts characters instead of bytes makes the safe version the
easy one.

Definition of done: TruncateString(s string, max int) string returns at most
max characters from the start of s, never cutting a multi-byte character, and
returns an empty string when max is zero or less. It has a doc comment and
table-driven tests covering a string shorter than the limit, a string exactly
at the limit, a string longer than the limit, a string of multi-byte
characters, a max of zero, and a negative max.

Model: opus-5

Cutting a string with a plain byte slice such as `s[:80]` will split a multi-byte character in half and produce invalid text, which shows up as a replacement character in logs, database columns and terminal output. A short function that counts characters instead of bytes makes the safe version the easy one. Definition of done: `TruncateString(s string, max int) string` returns at most max characters from the start of s, never cutting a multi-byte character, and returns an empty string when max is zero or less. It has a doc comment and table-driven tests covering a string shorter than the limit, a string exactly at the limit, a string longer than the limit, a string of multi-byte characters, a max of zero, and a negative max. Model: opus-5
sneak closed this issue 2026-09-05 05:45:41 +02:00
Sign in to join this conversation.
No Label
1 Participants
Notifications
Due Date
No due date set.
Dependencies

No dependencies set.

Reference: sneak/util#5