From 86d31aacec9c1fc75799c9bcdecc3a342b8f5319 Mon Sep 17 00:00:00 2001 From: chihiro-h Date: Sun, 1 Oct 2023 21:03:27 +0900 Subject: [PATCH] add: util for formatting bytes format --- internal/util.go | 19 +++++++++++++++++++ internal/util_test.go | 19 +++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 internal/util.go create mode 100644 internal/util_test.go diff --git a/internal/util.go b/internal/util.go new file mode 100644 index 0000000..bff5545 --- /dev/null +++ b/internal/util.go @@ -0,0 +1,19 @@ +package internal + +import ( + "fmt" +) + +// ref: https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/ +func formatBytes(b int64) string { + const unit = 1000 + if b < unit { + return fmt.Sprintf("%d", b) + } + div, exp := int64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f%c", float64(b)/float64(div), "KMGTPE"[exp]) +} diff --git a/internal/util_test.go b/internal/util_test.go new file mode 100644 index 0000000..54ace66 --- /dev/null +++ b/internal/util_test.go @@ -0,0 +1,19 @@ +package internal + +import "testing" + +func TestFormatBytes(t *testing.T) { + tests := map[int64]string{ + 999: "999", + 1024: "1.0K", + 1536: "1.5K", + 987654321: "987.7M", + } + for key, value := range tests { + got := formatBytes(key) + want := value + if got != want { + t.Fatalf("got: %v, want: %v\n", got, want) + } + } +}