Fix runeSliceWidthRange implementation (#1273)

* Fix `runeSliceWidthRange` implementation

* Add empty test case
This commit is contained in:
Joe Lim authored and GitHub committed 2023-06-04 16:22:46 +03:00
1 parent c3d44123bb
commit 014d18d3ea
2 files changed
+20 -8

No files matched your search

+11 -8
View File
@@ -31,23 +31,26 @@ func runeSliceWidth(rs []rune) int {
}
func runeSliceWidthRange(rs []rune, beg, end int) []rune {
if beg == end {
return []rune{}
}
curr := 0
b := 0
foundb := false
for i, r := range rs {
w := runewidth.RuneWidth(r)
switch {
case curr == beg:
if curr >= beg && !foundb {
b = i
case curr < beg && curr+w > beg:
b = i + 1
case curr == end:
foundb = true
}
if curr == end || curr+w > end {
return rs[b:i]
case curr > end:
return rs[b : i-1]
}
curr += w
}
return nil
return rs[b:]
}
// This function is used to escape whitespaces and special characters with
+9
View File
@@ -55,16 +55,25 @@ func TestRuneSliceWidthRange(t *testing.T) {
end int
exp []rune
}{
{[]rune{}, 0, 0, []rune{}},
{[]rune{'a', 'b', 'c', 'd'}, 1, 3, []rune{'b', 'c'}},
{[]rune{'a', 'ı', 'b', 'ş'}, 1, 3, []rune{'ı', 'b'}},
{[]rune{'世', '界', '世', '界'}, 2, 6, []rune{'界', '世'}},
{[]rune{'世', '界', '世', '界'}, 3, 6, []rune{'世'}},
{[]rune{'世', '界', '世', '界'}, 2, 5, []rune{'界'}},
{[]rune{'世', '界', '世', '界'}, 3, 5, []rune{}},
{[]rune{'世', '界', '世', '界'}, 4, 4, []rune{}},
{[]rune{'世', '界', '世', '界'}, 5, 5, []rune{}},
{[]rune{'世', '界', '世', '界'}, 4, 7, []rune{'世'}},
{[]rune{'世', '界', '世', '界'}, 4, 8, []rune{'世', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, 5, []rune{'a', '界'}},
{[]rune{'世', 'a', '界', 'ı'}, 2, 4, []rune{'a'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 5, []rune{'界'}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 4, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 3, 3, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 4, 4, []rune{}},
{[]rune{'世', 'a', '界', 'ı'}, 4, 6, []rune{'ı'}},
{[]rune{'世', 'a', '界', 'ı'}, 5, 6, []rune{'ı'}},
}
for _, test := range tests {