mirror of
https://github.com/VictoriaMetrics/VictoriaMetrics.git
synced 2024-11-21 14:44:00 +00:00
lib/stringsutil: add tests for LimitStringLen() function
This commit is contained in:
parent
4722b70c89
commit
6340911d38
2 changed files with 28 additions and 4 deletions
|
@ -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
lib/stringsutil/stringsutil_test.go
Normal file
24
lib/stringsutil/stringsutil_test.go
Normal file
|
@ -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")
|
||||
}
|
Loading…
Reference in a new issue