diff --git a/format.go b/format.go index de77992..3693259 100644 --- a/format.go +++ b/format.go @@ -1,9 +1,6 @@ package mpb -import ( - "fmt" - "strings" -) +import "fmt" const ( _ = iota @@ -16,7 +13,7 @@ type Units uint const ( - UnitNone Units = iota + _ = iota UnitBytes ) @@ -51,17 +48,16 @@ func formatBytes(i int64) (result string) { switch { - case i > bytesInTiB: + case i >= bytesInTiB: result = fmt.Sprintf("%.1fTiB", float64(i)/bytesInTiB) - case i > bytesInGiB: + case i >= bytesInGiB: result = fmt.Sprintf("%.1fGiB", float64(i)/bytesInGiB) - case i > bytesInMiB: + case i >= bytesInMiB: result = fmt.Sprintf("%.1fMiB", float64(i)/bytesInMiB) - case i > bytesInKiB: + case i >= bytesInKiB: result = fmt.Sprintf("%.1fKiB", float64(i)/bytesInKiB) default: result = fmt.Sprintf("%db", i) } - result = strings.Trim(result, " ") return } diff --git a/format_test.go b/format_test.go new file mode 100644 index 0000000..7529b62 --- /dev/null +++ b/format_test.go @@ -0,0 +1,51 @@ +package mpb_test + +import ( + "testing" + + "github.com/vbauerster/mpb" +) + +const ( + _ = iota + KiB = 1 << (iota * 10) + MiB + GiB + TiB +) + +func TestFormatNoUnits(t *testing.T) { + actual := mpb.Format(1234567).String() + expected := "1234567" + if actual != expected { + t.Errorf("Expected %q but found %q", expected, actual) + } +} + +func TestFormatWidth(t *testing.T) { + actual := mpb.Format(1234567).Width(10).String() + expected := " 1234567" + if actual != expected { + t.Errorf("Expected %q but found %q", expected, actual) + } +} + +func TestFormatToBytes(t *testing.T) { + inputs := []struct { + v int64 + e string + }{ + {v: 1000, e: "1000b"}, + {v: 1024, e: "1.0KiB"}, + {v: 3*MiB + 140*KiB, e: "3.1MiB"}, + {v: 2 * GiB, e: "2.0GiB"}, + {v: 4 * TiB, e: "4.0TiB"}, + } + + for _, input := range inputs { + actual := mpb.Format(input.v).To(mpb.UnitBytes).String() + if actual != input.e { + t.Errorf("Expected %q but found %q", input.e, actual) + } + } +}