From 9cf3325d5110c1ad7e504369ec90c7355ba348ce Mon Sep 17 00:00:00 2001 From: j178 <10510431+j178@users.noreply.github.com> Date: Sun, 19 Nov 2023 23:29:26 +0800 Subject: [PATCH] chore: improve long string truncate --- utils/str.go | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) diff --git a/utils/str.go b/utils/str.go index a9933853..0b15c59a 100644 --- a/utils/str.go +++ b/utils/str.go @@ -2,6 +2,7 @@ package utils import ( "encoding/hex" + "fmt" "strings" "unicode" "unicode/utf16" @@ -50,14 +51,15 @@ func EnsureTrailingNewline(s string) string { // TruncateString shortens a string longer than n by replacing the middle part with "......" func TruncateString(s string, n int) string { - if len(s) <= n { + if len(s) <= n || n < 30 { return s } - const l = len("......") - prefixLength := (n - l) / 2 - suffixLength := n - prefixLength - l + suffix := fmt.Sprintf("......<%d bytes truncated>", len(s)-30) + if n < len(suffix) { + return suffix + } - truncated := s[:prefixLength] + "......" + s[len(s)-suffixLength:] + truncated := s[:n-len(suffix)] + suffix return truncated }