1
0
forked from sneak/util

add TruncateString for shortening a string safely

TruncateString returns at most the requested number of characters from the
start of a string, counting characters rather than bytes so a multi-byte
character is never cut in half. Comes with a doc comment and table-driven
tests. (closes #5)

Model: opus-5
This commit is contained in:
2026-09-05 03:25:08 +00:00
parent 9302c14a6c
commit daaea4e10f
2 changed files with 62 additions and 0 deletions

21
truncate.go Normal file
View File

@@ -0,0 +1,21 @@
package util
// TruncateString returns at most max characters from the start of s. It counts
// characters rather than bytes, so a multi-byte character is never cut in half
// and the result is always valid text. A max of zero or less returns an empty
// string, and a string already at or below the limit is returned unchanged.
func TruncateString(s string, max int) string {
if max <= 0 {
return ""
}
count := 0
for offset := range s {
if count == max {
return s[:offset]
}
count++
}
return s
}