fix: handle negative truncate lengths (#744)

This commit is contained in:
陈家名
2026-05-07 11:40:04 +08:00
committed by GitHub
parent 8f410ab140
commit eed802c814
2 changed files with 9 additions and 0 deletions

View File

@@ -5,6 +5,9 @@ package util
// TruncateStr truncates s to at most n runes, safe for multi-byte (e.g. CJK) characters.
func TruncateStr(s string, n int) string {
if n <= 0 {
return ""
}
r := []rune(s)
if len(r) <= n {
return s
@@ -14,6 +17,9 @@ func TruncateStr(s string, n int) string {
// TruncateStrWithEllipsis truncates s to at most n runes (including "..." suffix).
func TruncateStrWithEllipsis(s string, n int) string {
if n <= 0 {
return ""
}
r := []rune(s)
if len(r) <= n {
return s

View File

@@ -17,6 +17,7 @@ func TestTruncateStr(t *testing.T) {
{"truncate", "hello world", 5, "hello"},
{"empty", "", 5, ""},
{"zero limit", "hello", 0, ""},
{"negative limit", "hello", -1, ""},
{"CJK characters", "你好世界测试", 4, "你好世界"},
}
for _, tt := range tests {
@@ -41,6 +42,8 @@ func TestTruncateStrWithEllipsis(t *testing.T) {
{"limit less than 3", "hello", 2, "he"},
{"limit equals 3", "hello world", 3, "..."},
{"empty", "", 5, ""},
{"zero limit", "hello", 0, ""},
{"negative limit", "hello", -1, ""},
{"CJK with ellipsis", "你好世界测试", 5, "你好..."},
}
for _, tt := range tests {