Improve duration humanization. (#4071)

This commit is contained in:
Bala FA
2017-04-26 16:08:35 +05:30
committed by Harshavardhana
parent 64c1c0f37d
commit cf1fc45142
13 changed files with 167 additions and 260 deletions

View File

@@ -84,7 +84,7 @@ func humanateBytes(s uint64, base float64, sizes []string) string {
//
// See also: ParseBytes.
//
// Bytes(82854982) -> 83MB
// Bytes(82854982) -> 83 MB
func Bytes(s uint64) string {
sizes := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB"}
return humanateBytes(s, 1000, sizes)
@@ -94,7 +94,7 @@ func Bytes(s uint64) string {
//
// See also: ParseBytes.
//
// IBytes(82854982) -> 79MiB
// IBytes(82854982) -> 79 MiB
func IBytes(s uint64) string {
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
return humanateBytes(s, 1024, sizes)
@@ -105,18 +105,27 @@ func IBytes(s uint64) string {
//
// See Also: Bytes, IBytes.
//
// ParseBytes("42MB") -> 42000000, nil
// ParseBytes("42mib") -> 44040192, nil
// ParseBytes("42 MB") -> 42000000, nil
// ParseBytes("42 mib") -> 44040192, nil
func ParseBytes(s string) (uint64, error) {
lastDigit := 0
hasComma := false
for _, r := range s {
if !(unicode.IsDigit(r) || r == '.') {
if !(unicode.IsDigit(r) || r == '.' || r == ',') {
break
}
if r == ',' {
hasComma = true
}
lastDigit++
}
f, err := strconv.ParseFloat(s[:lastDigit], 64)
num := s[:lastDigit]
if hasComma {
num = strings.Replace(num, ",", "", -1)
}
f, err := strconv.ParseFloat(num, 64)
if err != nil {
return 0, err
}