From 41ab43cbe6cf9fec3078cc6c0fc8d243f2371c50 Mon Sep 17 00:00:00 2001 From: Arran Walker Date: Wed, 24 Oct 2018 14:57:05 +0000 Subject: [PATCH] Fix humanize's FormatByteRate() to work with 0s duration On Windows, occasionally: t := time.Now() ... humanize.FormatByteRate(size, time.Since(t)) will result in time.Since returning 0. This commit clamps the duration to be at least 1 nanosecond. --- tools/humanize/humanize.go | 2 +- tools/humanize/humanize_test.go | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tools/humanize/humanize.go b/tools/humanize/humanize.go index 2d6023ec..7aad4c16 100644 --- a/tools/humanize/humanize.go +++ b/tools/humanize/humanize.go @@ -146,7 +146,7 @@ func FormatByteRate(s uint64, d time.Duration) string { f := float64(s) if f != 0 { - f = f / d.Seconds() + f = f / math.Max(time.Nanosecond.Seconds(), d.Seconds()) e = math.Floor(log(f, 1000)) if e <= eps { // The result of math.Floor(log(r, 1000)) can be diff --git a/tools/humanize/humanize_test.go b/tools/humanize/humanize_test.go index c151254e..49422a36 100644 --- a/tools/humanize/humanize_test.go +++ b/tools/humanize/humanize_test.go @@ -273,7 +273,8 @@ func TestFormateByteRate(t *testing.T) { "format petabytes exact": {uint64(1.3 * math.Pow(10, 12)), time.Second, "1.3 TB/s"}, "format terabytes exact": {uint64(1.3 * math.Pow(10, 15)), time.Second, "1.3 PB/s"}, - "format bytes (non-second)": {uint64(10 * math.Pow(10, 0)), 2 * time.Second, "5 B/s"}, + "format bytes (non-second)": {uint64(10 * math.Pow(10, 0)), 2 * time.Second, "5 B/s"}, + "format bytes (zero-second)": {uint64(10 * math.Pow(10, 0)), 0, "10 GB/s"}, } { t.Run(desc, c.Assert) }