Skip to content

Commit 9cf3325

Browse files
committed
chore: improve long string truncate
1 parent 796c13a commit 9cf3325

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

utils/str.go

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package utils
22

33
import (
44
"encoding/hex"
5+
"fmt"
56
"strings"
67
"unicode"
78
"unicode/utf16"
@@ -50,14 +51,15 @@ func EnsureTrailingNewline(s string) string {
5051

5152
// TruncateString shortens a string longer than n by replacing the middle part with "...<truncated>..."
5253
func TruncateString(s string, n int) string {
53-
if len(s) <= n {
54+
if len(s) <= n || n < 30 {
5455
return s
5556
}
56-
const l = len("...<truncated>...")
57-
prefixLength := (n - l) / 2
58-
suffixLength := n - prefixLength - l
57+
suffix := fmt.Sprintf("......<%d bytes truncated>", len(s)-30)
58+
if n < len(suffix) {
59+
return suffix
60+
}
5961

60-
truncated := s[:prefixLength] + "...<truncated>..." + s[len(s)-suffixLength:]
62+
truncated := s[:n-len(suffix)] + suffix
6163

6264
return truncated
6365
}

0 commit comments

Comments
 (0)