fix(strutil): keep center-aligned Resize within the requested length
The center branch of resize() added the odd-padding space whenever the input was non-empty, because the parity check omitted the source length (wantLen - padLn*2 instead of wantLen - sLen - padLn*2). This made Resize, Align and their utf8 variants overflow wantLen by one for every non-empty string with an even amount of padding. Subtract sLen so the extra space is only added when the total padding is actually odd.
This commit is contained in:
1 parent
b17a55589a
commit
e2e5b5495f
3 files changed
+99
-1
No files matched your search
@@ -38,6 +38,29 @@ func TestPadding(t *testing.T) {
|
||||
assert.Eq(t, "hi,你好000", strutil.Utf8Padding(s, "0", 10, strutil.PosRight))
|
||||
}
|
||||
|
||||
func TestResize_center_length(t *testing.T) {
|
||||
// Center alignment must always produce a string of exactly the requested
|
||||
// length; the extra padding space is only needed when the total padding
|
||||
// (wantLen - len(s)) is odd.
|
||||
tests := []struct {
|
||||
give string
|
||||
len int
|
||||
want string
|
||||
}{
|
||||
{"ab", 6, " ab "}, // even padding (4): 2 + 2
|
||||
{"ab", 4, " ab "}, // even padding (2): 1 + 1
|
||||
{"ab", 5, " ab "}, // odd padding (3): 1 + 2
|
||||
{"abc", 7, " abc "}, // even padding (4): 2 + 2
|
||||
{"a", 4, " a "}, // odd padding (3): 1 + 2
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
got := strutil.Resize(tt.give, tt.len, comdef.Center)
|
||||
assert.Eq(t, tt.len, len(got), "Resize(%q,%d,Center)=%q", tt.give, tt.len, got)
|
||||
assert.Eq(t, tt.want, got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResize(t *testing.T) {
|
||||
tests := []struct {
|
||||
want, give string
|
||||
|
||||
Reference in new issue
Block a user