diff --git a/fs/config.go b/fs/config.go index faf7e02cb..1b5987fd3 100644 --- a/fs/config.go +++ b/fs/config.go @@ -6,6 +6,7 @@ import ( "bufio" "fmt" "log" + "math" "os" "os/user" "path" @@ -46,21 +47,30 @@ var ( ) func init() { - pflag.VarP(&bwLimit, "bwlimit", "", "Bandwidth limit in kBytes/s, or use suffix K|M|G") + pflag.VarP(&bwLimit, "bwlimit", "", "Bandwidth limit in kBytes/s, or use suffix k|M|G") } // Turn SizeSuffix into a string -func (x *SizeSuffix) String() string { +func (x SizeSuffix) String() string { + scaled := float64(0) + suffix := "" switch { - case *x == 0: + case x == 0: return "0" - case *x < 1024*1024: - return fmt.Sprintf("%.3fk", float64(*x)/1024) - case *x < 1024*1024*1024: - return fmt.Sprintf("%.3fM", float64(*x)/1024/1024) + case x < 1024*1024: + scaled = float64(x) / 1024 + suffix = "k" + case x < 1024*1024*1024: + scaled = float64(x) / 1024 / 1024 + suffix = "M" default: - return fmt.Sprintf("%.3fG", float64(*x)/1024/1024/1024) + scaled = float64(x) / 1024 / 1024 / 1024 + suffix = "G" } + if math.Floor(scaled) == scaled { + return fmt.Sprintf("%.0f%s", scaled, suffix) + } + return fmt.Sprintf("%.3f%s", scaled, suffix) } // Set a SizeSuffix @@ -89,6 +99,9 @@ func (x *SizeSuffix) Set(s string) error { if err != nil { return err } + if value < 0 { + return fmt.Errorf("Size can't be negative %q", s) + } value *= multiplier *x = SizeSuffix(value) return nil diff --git a/fs/config_test.go b/fs/config_test.go index f0989ece9..00bb6d723 100644 --- a/fs/config_test.go +++ b/fs/config_test.go @@ -9,10 +9,11 @@ func TestSizeSuffixString(t *testing.T) { }{ {0, "0"}, {102, "0.100k"}, - {1024, "1.000k"}, - {1024 * 1024, "1.000M"}, - {1024 * 1024 * 1024, "1.000G"}, - {10 * 1024 * 1024 * 1024, "10.000G"}, + {1024, "1k"}, + {1024 * 1024, "1M"}, + {1024 * 1024 * 1024, "1G"}, + {10 * 1024 * 1024 * 1024, "10G"}, + {10.1 * 1024 * 1024 * 1024, "10.100G"}, } { ss := SizeSuffix(test.in) got := ss.String() @@ -41,6 +42,7 @@ func TestSizeSuffixSet(t *testing.T) { {"1p", 0, true}, {"1.p", 0, true}, {"1p", 0, true}, + {"-1K", 0, true}, } { ss := SizeSuffix(0) err := ss.Set(test.in)