Просмотр исходного кода

Saving some bytes

Signed-off-by: Vishal Rana <vr@labstack.com>
Vishal Rana 10 лет назад
Родитель
Сommit
2219395d0e
2 измененных файлов с 8 добавлено и 8 удалено
  1. 6 6
      bytes/bytes.go
  2. 2 2
      bytes/bytes_test.go

+ 6 - 6
bytes/bytes.go

@@ -1,7 +1,6 @@
 package bytes
 
 import (
-	"bytes"
 	"fmt"
 	"math"
 )
@@ -26,12 +25,13 @@ func format(b float64, bin bool) string {
 	if b < unit {
 		return fmt.Sprintf("%.0f B", b)
 	} else {
-		exp := math.Floor(math.Log(b) / math.Log(unit))
-		pfx := new(bytes.Buffer)
-		pfx.WriteByte("KMGTPE"[uint8(exp)-1])
+		i := uint8(math.Floor(math.Log(b) / math.Log(unit)))
+		pre := make([]byte, 1, 2)
+		pre[0] = "KMGTPE"[i-1]
 		if bin {
-			pfx.WriteString("i")
+			pre = pre[:2]
+			pre[1] = 'i'
 		}
-		return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, exp), pfx)
+		return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, i), pre)
 	}
 }

+ 2 - 2
bytes/bytes_test.go

@@ -18,13 +18,13 @@ func TestFormat(t *testing.T) {
 	// Exact
 	f = Format(1000 * 1000 * 1000)
 	if f != "1.00 GB" {
-		t.Errorf("formatted bytes should be 1.00 GB, found %s", f)
+		t.Errorf("formatted bytes should be 1.00 GB, found %s xxx", f)
 	}
 }
 
 func TestFormatB(t *testing.T) {
 	f := FormatB(1323)
 	if f != "1.29 KiB" {
-		t.Errorf("formatted bytes should be 1.29 KiB, found %s", f)
+		t.Errorf("formatted bytes should be 1.29 KiB, found %s xxx", f)
 	}
 }