Implement stringutils.Ellipsis()

This patch implements an Ellipsis utility to
append an ellipsis (...)  when truncating
strings in output.

It also fixes the existing Truncate() utility
to be compatible with unicode/multibyte characters.

Signed-off-by: Sebastiaan van Stijn <github@gone.nl>
Upstream-commit: 51dc35cf23a5418e93128854bedc2e59d8ca743a
Component: engine
This commit is contained in:
Sebastiaan van Stijn
2016-08-11 14:14:06 +02:00
parent adf210319c
commit 60e441e430
7 changed files with 52 additions and 22 deletions
@@ -32,12 +32,26 @@ func GenerateRandomASCIIString(n int) string {
return string(res)
}
// Truncate truncates a string to maxlen.
func Truncate(s string, maxlen int) string {
if len(s) <= maxlen {
// Ellipsis truncates a string to fit within maxlen, and appends ellipsis (...).
// For maxlen of 3 and lower, no ellipsis is appended.
func Ellipsis(s string, maxlen int) string {
r := []rune(s)
if len(r) <= maxlen {
return s
}
return s[:maxlen]
if maxlen <= 3 {
return string(r[:maxlen])
}
return string(r[:maxlen-3]) + "..."
}
// Truncate truncates a string to maxlen.
func Truncate(s string, maxlen int) string {
r := []rune(s)
if len(r) <= maxlen {
return s
}
return string(r[:maxlen])
}
// InSlice tests whether a string is contained in a slice of strings or not.
@@ -57,24 +57,40 @@ func TestGenerateRandomAsciiStringIsAscii(t *testing.T) {
}
}
func TestEllipsis(t *testing.T) {
str := "t🐳ststring"
newstr := Ellipsis(str, 3)
if newstr != "t🐳s" {
t.Fatalf("Expected t🐳s, got %s", newstr)
}
newstr = Ellipsis(str, 8)
if newstr != "t🐳sts..." {
t.Fatalf("Expected tests..., got %s", newstr)
}
newstr = Ellipsis(str, 20)
if newstr != "t🐳ststring" {
t.Fatalf("Expected t🐳ststring, got %s", newstr)
}
}
func TestTruncate(t *testing.T) {
str := "teststring"
str := "t🐳ststring"
newstr := Truncate(str, 4)
if newstr != "test" {
t.Fatalf("Expected test, got %s", newstr)
if newstr != "t🐳st" {
t.Fatalf("Expected t🐳st, got %s", newstr)
}
newstr = Truncate(str, 20)
if newstr != "teststring" {
t.Fatalf("Expected teststring, got %s", newstr)
if newstr != "t🐳ststring" {
t.Fatalf("Expected t🐳ststring, got %s", newstr)
}
}
func TestInSlice(t *testing.T) {
slice := []string{"test", "in", "slice"}
slice := []string{"t🐳st", "in", "slice"}
test := InSlice(slice, "test")
test := InSlice(slice, "t🐳st")
if !test {
t.Fatalf("Expected string test to be in slice")
t.Fatalf("Expected string t🐳st to be in slice")
}
test = InSlice(slice, "SLICE")
if !test {