Skip to content

Commit

Permalink
chore: improve long string truncate
Browse files Browse the repository at this point in the history
  • Loading branch information
j178 committed Nov 19, 2023
1 parent 796c13a commit 9cf3325
Showing 1 changed file with 7 additions and 5 deletions.
12 changes: 7 additions & 5 deletions utils/str.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"encoding/hex"
"fmt"
"strings"
"unicode"
"unicode/utf16"
Expand Down Expand Up @@ -50,14 +51,15 @@ func EnsureTrailingNewline(s string) string {

// TruncateString shortens a string longer than n by replacing the middle part with "...<truncated>..."
func TruncateString(s string, n int) string {
if len(s) <= n {
if len(s) <= n || n < 30 {
return s
}
const l = len("...<truncated>...")
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] + "...<truncated>..." + s[len(s)-suffixLength:]
truncated := s[:n-len(suffix)] + suffix

return truncated
}
Expand Down

0 comments on commit 9cf3325

Please sign in to comment.