Skip to content

Commit

Permalink
lib/stringsutil: add tests for LimitStringLen() function
Browse files Browse the repository at this point in the history
  • Loading branch information
valyala committed Nov 13, 2023
1 parent 4722b70 commit 6340911
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
8 changes: 4 additions & 4 deletions lib/stringsutil/stringsutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ package stringsutil
// If len(s) > maxLen, then s is replaced with "s_prefix..s_suffix",
// so the total length of the returned string doesn't exceed maxLen.
func LimitStringLen(s string, maxLen int) string {
if len(s) <= maxLen || maxLen < 4 {
if maxLen < 4 {
maxLen = 4
}
if len(s) <= maxLen {
return s
}
n := (maxLen / 2) - 1
if n < 0 {
n = 0
}
return s[:n] + ".." + s[len(s)-n:]
}
24 changes: 24 additions & 0 deletions lib/stringsutil/stringsutil_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package stringsutil

import (
"testing"
)

func TestLimitStringLen(t *testing.T) {
f := func(s string, maxLen int, resultExpected string) {
t.Helper()

result := LimitStringLen(s, maxLen)
if result != resultExpected {
t.Fatalf("unexpected result; got %q; want %q", result, resultExpected)
}
}

f("", 1, "")
f("a", 10, "a")
f("abc", 2, "abc")
f("abcd", 3, "abcd")
f("abcde", 3, "a..e")
f("abcde", 4, "a..e")
f("abcde", 5, "abcde")
}

0 comments on commit 6340911

Please sign in to comment.