File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -22,6 +22,21 @@ func DataSize(size uint64) string {
2222 }
2323}
2424
25+ // FormatBytes Format the byte size to be a readable string. eg: 1024 => 1 KB
26+ func FormatBytes (bytes int ) string {
27+ const unit = 1024
28+ if bytes < unit {
29+ return fmt .Sprintf ("%d B" , bytes )
30+ }
31+
32+ div , exp := int64 (unit ), 0
33+ for n := bytes / unit ; n >= unit ; n /= unit {
34+ div *= unit
35+ exp ++
36+ }
37+ return fmt .Sprintf ("%.2f %cB" , float64 (bytes )/ float64 (div ), "KMGTPE" [exp ])
38+ }
39+
2540var timeFormats = [][]int {
2641 {0 },
2742 {1 },
Original file line number Diff line number Diff line change @@ -24,6 +24,25 @@ func TestDataSize(t *testing.T) {
2424 }
2525}
2626
27+ func TestFormatBytes (t * testing.T ) {
28+ tests := []struct {
29+ input int
30+ expected string
31+ }{
32+ {0 , "0 B" },
33+ {1024 , "1.00 KB" },
34+ {1536 , "1.50 KB" },
35+ {1048576 , "1.00 MB" },
36+ {1073741824 , "1.00 GB" },
37+ {1200346778 , "1.12 GB" },
38+ }
39+
40+ for _ , tt := range tests {
41+ result := mathutil .FormatBytes (tt .input )
42+ assert .Eq (t , tt .expected , result )
43+ }
44+ }
45+
2746func TestHowLongAgo (t * testing.T ) {
2847 tests := []struct {
2948 args int64
You can’t perform that action at this time.
0 commit comments