Skip to content

Commit 6dd6b6e

Browse files
authored
fix(bytes): trim surrounding whitespace in Parse (#66)
Values like " 12KiB " failed to parse even though the same number with an internal space ("12 KiB") already works. Trim leading and trailing whitespace before matching.
1 parent 60bbdf4 commit 6dd6b6e

2 files changed

Lines changed: 13 additions & 0 deletions

File tree

bytes/bytes.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,7 @@ func (*Bytes) FormatDecimal(value int64) string {
122122
// For example, 6GiB (6Gi is also valid) will return 6442450944, and
123123
// 6GB (6G is also valid) will return 6000000000.
124124
func (b *Bytes) Parse(value string) (int64, error) {
125+
value = strings.TrimSpace(value)
125126

126127
i, err := b.ParseBinary(value)
127128
if err == nil {
@@ -134,6 +135,7 @@ func (b *Bytes) Parse(value string) (int64, error) {
134135
// ParseBinary parses human readable bytes string to bytes integer.
135136
// For example, 6GiB (6Gi is also valid) will return 6442450944.
136137
func (*Bytes) ParseBinary(value string) (i int64, err error) {
138+
value = strings.TrimSpace(value)
137139
parts := patternBinary.FindStringSubmatch(value)
138140
if len(parts) < 3 {
139141
return 0, fmt.Errorf("error parsing value=%s", value)
@@ -166,6 +168,7 @@ func (*Bytes) ParseBinary(value string) (i int64, err error) {
166168
// ParseDecimal parses human readable bytes string to bytes integer.
167169
// For example, 6GB (6G is also valid) will return 6000000000.
168170
func (*Bytes) ParseDecimal(value string) (i int64, err error) {
171+
value = strings.TrimSpace(value)
169172
parts := patternDecimal.FindStringSubmatch(value)
170173
if len(parts) < 3 {
171174
return 0, fmt.Errorf("error parsing value=%s", value)

bytes/bytes_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,3 +400,13 @@ func TestBytesParse(t *testing.T) {
400400
assert.Equal(t, int64(8000000000000000000), b)
401401
}
402402
}
403+
404+
func TestBytesParseTrimSpace(t *testing.T) {
405+
b, err := Parse(" 12KiB ")
406+
assert.NoError(t, err)
407+
assert.Equal(t, int64(12288), b)
408+
409+
b, err = Parse("\t6GiB\n")
410+
assert.NoError(t, err)
411+
assert.Equal(t, int64(6442450944), b)
412+
}

0 commit comments

Comments
 (0)