feat: cli

This commit is contained in:
liwei committed 2021-03-25 17:30:40 +08:00
1 parent caf9bf265b
commit 359f28bb1f
12 files changed
+209 -97

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
package util
import (
"fmt"
"math"
)
var unitArr = []string{"B", "KB", "MB", "GB", "TB", "EB"}
func ByteFmt(size int64) string {
if size == 0 {
return "unknown"
}
fs := float64(size)
p := int(math.Log(fs) / math.Log(1024))
val := fs / math.Pow(1024, float64(p))
_, frac := math.Modf(val)
if frac > 0 {
return fmt.Sprintf("%.1f%s", math.Floor(val*10)/10, unitArr[p])
} else {
return fmt.Sprintf("%d%s", int(val), unitArr[p])
}
}
+57
View File
@@ -0,0 +1,57 @@
package util
import "testing"
func TestByteFmt(t *testing.T) {
type args struct {
size int64
}
tests := []struct {
name string
args args
want string
}{
{
name: "100B",
args: args{size: int64(100)},
want: "100B",
},
{
name: "1KB",
args: args{size: int64(1024)},
want: "1KB",
},
{
name: "1.9KB",
args: args{size: int64(1024*2 - 1)},
want: "1.9KB",
},
{
name: "2KB",
args: args{size: int64(1024 * 2)},
want: "2KB",
},
{
name: "1MB",
args: args{size: int64(1024 * 1024)},
want: "1MB",
},
{
name: "1.9MB",
args: args{size: int64(1024*1024*2 - 1)},
want: "1.9MB",
},
{
name: "2MB",
args: args{size: int64(1024 * 1024 * 2)},
want: "2MB",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := ByteFmt(tt.args.size); got != tt.want {
t.Errorf("ByteFmt() = %v, want %v", got, tt.want)
}
})
}
}