瀏覽代碼

switch to SI standard and add test

Victor Vieux 12 年之前
父節點
當前提交
b45143da9b
共有 2 個文件被更改,包括 17 次插入5 次删除
  1. 4 5
      utils/utils.go
  2. 13 0
      utils/utils_test.go

+ 4 - 5
utils/utils.go

@@ -133,20 +133,19 @@ func HumanDuration(d time.Duration) string {
 }
 
 // HumanSize returns a human-readable approximation of a size
-// (eg. "44kB", "17MB")
+// using SI standard (eg. "44kB", "17MB")
 func HumanSize(size int64) string {
 	i := 0
 	var sizef float64
 	sizef = float64(size)
 	units := []string{"B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"}
-	for sizef > 1024.0 {
-		sizef = sizef / 1024.0
+	for sizef >= 1000.0 {
+		sizef = sizef / 1000.0
 		i++
 	}
-	return fmt.Sprintf("%.*f %s", i, sizef, units[i])
+	return fmt.Sprintf("%.4g %s", sizef, units[i])
 }
 
-
 func Trunc(s string, maxlen int) string {
 	if len(s) <= maxlen {
 		return s

+ 13 - 0
utils/utils_test.go

@@ -261,3 +261,16 @@ func TestCompareKernelVersion(t *testing.T) {
 		&KernelVersionInfo{Kernel: 3, Major: 8, Minor: 0, Flavor: "0"},
 		-1)
 }
+
+func TestHumanSize(t *testing.T) {
+
+	size1000 := HumanSize(1000)
+	if size1000 != "1 kB" {
+		t.Errorf("1000 -> expected 1 kB, got %s", size1000)
+	}
+
+	size1024 := HumanSize(1024)
+	if size1024 != "1.024 kB" {
+		t.Errorf("1024 -> expected 1.024 kB, got %s", size1024)
+	}
+}