diff options
author | Sean E. Russell <ser@ser1.net> | 2020-02-14 09:35:58 -0600 |
---|---|---|
committer | Sean E. Russell <ser@ser1.net> | 2020-02-14 09:35:58 -0600 |
commit | f850a47d91d413de40de219aa597ade41a05f757 (patch) | |
tree | fa15d4e8ddc62888788d6814e4ab3c010931d892 /utils | |
parent | 64d4a81212a43a4b805b92963fd4da230b3ca313 (diff) | |
parent | 246ebfbff2c87f66218c42ea9490214006f2efc8 (diff) |
Merge remote-tracking branch 'rephorm/filter'
Diffstat (limited to 'utils')
-rw-r--r-- | utils/runes.go | 24 | ||||
-rw-r--r-- | utils/runes_test.go | 50 |
2 files changed, 74 insertions, 0 deletions
diff --git a/utils/runes.go b/utils/runes.go new file mode 100644 index 0000000..76cb5e3 --- /dev/null +++ b/utils/runes.go @@ -0,0 +1,24 @@ +package utils + +import ( + rw "github.com/mattn/go-runewidth" +) + +func TruncateFront(s string, w int, prefix string) string { + if rw.StringWidth(s) <= w { + return s + } + r := []rune(s) + pw := rw.StringWidth(prefix) + w -= pw + width := 0 + i := len(r) - 1 + for ; i >= 0; i-- { + cw := rw.RuneWidth(r[i]) + width += cw + if width > w { + break + } + } + return prefix + string(r[i+1:len(r)]) +} diff --git a/utils/runes_test.go b/utils/runes_test.go new file mode 100644 index 0000000..67ceefc --- /dev/null +++ b/utils/runes_test.go @@ -0,0 +1,50 @@ +package utils + +import "testing" + +const ( + ELLIPSIS = "…" +) + +func TestTruncateFront(t *testing.T) { + tests := []struct { + s string + w int + prefix string + want string + }{ + {"", 0, ELLIPSIS, ""}, + {"", 1, ELLIPSIS, ""}, + {"", 10, ELLIPSIS, ""}, + + {"abcdef", 0, ELLIPSIS, ELLIPSIS}, + {"abcdef", 1, ELLIPSIS, ELLIPSIS}, + {"abcdef", 2, ELLIPSIS, ELLIPSIS + "f"}, + {"abcdef", 5, ELLIPSIS, ELLIPSIS + "cdef"}, + {"abcdef", 6, ELLIPSIS, "abcdef"}, + {"abcdef", 10, ELLIPSIS, "abcdef"}, + + {"abcdef", 0, "...", "..."}, + {"abcdef", 1, "...", "..."}, + {"abcdef", 3, "...", "..."}, + {"abcdef", 4, "...", "...f"}, + {"abcdef", 5, "...", "...ef"}, + {"abcdef", 6, "...", "abcdef"}, + {"abcdef", 10, "...", "abcdef"}, + + {"⦅full~width⦆", 15, ".", "⦅full~width⦆"}, + {"⦅full~width⦆", 14, ".", ".full~width⦆"}, + {"⦅full~width⦆", 13, ".", ".ull~width⦆"}, + {"⦅full~width⦆", 10, ".", ".~width⦆"}, + {"⦅full~width⦆", 9, ".", ".width⦆"}, + {"⦅full~width⦆", 8, ".", ".width⦆"}, + {"⦅full~width⦆", 3, ".", ".⦆"}, + {"⦅full~width⦆", 2, ".", "."}, + } + + for _, test := range tests { + if got := TruncateFront(test.s, test.w, test.prefix); got != test.want { + t.Errorf("TruncateFront(%q, %d, %q) = %q; want %q", test.s, test.w, test.prefix, got, test.want) + } + } +} |