Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions bytes.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package humanize
import (
"fmt"
"math"
"math/bits"
"strconv"
"strings"
"unicode"
Expand Down Expand Up @@ -170,6 +171,18 @@ func ParseBytes(s string) (uint64, error) {

extra := strings.ToLower(strings.TrimSpace(s[lastDigit:]))
if m, ok := bytesSizeTable[extra]; ok {
// Parse whole-number inputs exactly. A float64 cannot represent
// integers above 2^53, and the multiplication below would also reject
// otherwise-valid values near math.MaxUint64, so route integers through
// uint64 arithmetic with an overflow check.
if !strings.ContainsRune(num, '.') {
if v, perr := strconv.ParseUint(num, 10, 64); perr == nil {
if hi, lo := bits.Mul64(v, m); hi == 0 {
return lo, nil
}
return 0, fmt.Errorf("too large: %v", s)
}
}
f *= float64(m)
if f >= math.MaxUint64 {
return 0, fmt.Errorf("too large: %v", s)
Expand Down
24 changes: 24 additions & 0 deletions bytes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,30 @@ func TestByteErrors(t *testing.T) {
}
}

func TestParseBytesExactIntegers(t *testing.T) {
// Whole-number byte counts must be parsed exactly, including values a
// float64 cannot represent and the full uint64 range.
tests := []struct {
in string
exp uint64
}{
{"9007199254740993", 9007199254740993}, // 2^53 + 1
{"9007199254740993B", 9007199254740993}, // same, with suffix
{"18446744073709551615", 18446744073709551615}, // math.MaxUint64
{"18446744073709551615 B", 18446744073709551615},
}
for _, p := range tests {
got, err := ParseBytes(p.in)
if err != nil {
t.Errorf("Couldn't parse %v: %v", p.in, err)
continue
}
if got != p.exp {
t.Errorf("Expected %d for %q, got %d", p.exp, p.in, got)
}
}
}

func TestBytes(t *testing.T) {
testList{
{"bytes(0)", Bytes(0), "0 B"},
Expand Down