From 05e1e18ea522156116fb896c2006586aefcc4947 Mon Sep 17 00:00:00 2001 From: gan-of-culture Date: Mon, 5 Sep 2022 05:20:18 +0200 Subject: [PATCH] [FIX] option -i: now shows the sizes with the correct units --- utils/utils.go | 15 +++++++++++++++ utils/utils_test.go | 23 +++++++++++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/utils/utils.go b/utils/utils.go index 56d19c3..e5ad765 100755 --- a/utils/utils.go +++ b/utils/utils.go @@ -33,6 +33,21 @@ func CalcSizeInByte(number float64, unit string) int64 { return int64(number) } +// ByteCountSI turn bytes to SI (decimal) format - https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/ +func ByteCountSI(b int64) string { + const unit = 1000 + if b < unit { + return fmt.Sprintf("%d B", b) + } + div, exp := int64(unit), 0 + for n := b / unit; n >= unit; n /= unit { + div *= unit + exp++ + } + return fmt.Sprintf("%.1f %cB", + float64(b)/float64(div), "kMGTPE"[exp]) +} + // NeedDownloadList return the indices of gallery that need download func NeedDownloadList(length int) []int { if config.Pages != "" { diff --git a/utils/utils_test.go b/utils/utils_test.go index 0f8b3f5..d506fe0 100755 --- a/utils/utils_test.go +++ b/utils/utils_test.go @@ -57,6 +57,29 @@ func TestCalcSizeInByte(t *testing.T) { } } +func TestByteCountSI(t *testing.T) { + tests := []struct { + Name string + number int64 + Want string + }{ + { + Name: "To Kilobytes", + number: 752000, + Want: "752.0 kB", + }, + } + for _, tt := range tests { + t.Run(tt.Name, func(t *testing.T) { + bytes := ByteCountSI(tt.number) + + if bytes != tt.Want { + t.Errorf("Got: %v - Want: %v", bytes, tt.Want) + } + }) + } +} + func TestNeedDownloadList(t *testing.T) { type args struct { len int