diff --git a/lib/stringsutil/stringsutil.go b/lib/stringsutil/stringsutil.go index 96afb208c..034612292 100644 --- a/lib/stringsutil/stringsutil.go +++ b/lib/stringsutil/stringsutil.go @@ -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:] } diff --git a/lib/stringsutil/stringsutil_test.go b/lib/stringsutil/stringsutil_test.go new file mode 100644 index 000000000..bda93fe4f --- /dev/null +++ b/lib/stringsutil/stringsutil_test.go @@ -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") +}