Ver código fonte

Fixed issues based on some suggestions

Signed-off-by: Vishal Rana <vr@labstack.com>
Vishal Rana 10 anos atrás
pai
commit
e3eb0ca2c3
3 arquivos alterados com 31 adições e 30 exclusões
  1. 3 4
      bytes/README.md
  2. 23 20
      bytes/bytes.go
  3. 5 6
      bytes/bytes_test.go

+ 3 - 4
bytes/README.md

@@ -4,7 +4,7 @@ Format bytes to string
 
 ## Installation
 
-```go get github.com/labstack/gommon/color```
+```go get github.com/labstack/gommon/bytes```
 
 ## [Usage](https://github.com/labstack/gommon/blob/master/bytes/bytes_test.go)
 
@@ -14,13 +14,12 @@ Format bytes to string
 fmt.Println(bytes.Format(1323))
 ```
 
-`1.29 KB`
+`1.32 KB`
 
 ### Binary prefix
 
 ```go
-bytes.BinaryPrefix(true)
-fmt.Println(bytes.Format(1323))
+fmt.Println(bytes.FormatBin(1323))
 ```
 
 `1.29 KiB`

+ 23 - 20
bytes/bytes.go

@@ -1,33 +1,36 @@
 package bytes
 
 import (
+	"bytes"
 	"fmt"
 	"math"
 )
 
-var (
-	sfx = "B"
-)
-
-// BinaryPrefix sets binary prefix as specified by ICE standard. For example, 13.23 MiB.
-func BinaryPrefix(on bool) {
-	if on {
-		sfx = "iB"
-	} else {
-		sfx = "B"
-	}
+// Format formats bytes to string. For example, 1024 returns 1 KB
+func Format(b uint64) string {
+	return format(float64(b), false)
 }
 
-// Bytes formats bytes into string. For example, 1024 returns 1 KB
-func Format(b uint64) string {
-	n := float64(b)
-	unit := float64(1024)
+// FormatBin formats bytes to string as specified by ICE standard. For example,
+// 13.23 MiB.
+func FormatBin(b uint64) string {
+	return format(float64(b), true)
+}
 
-	if n < unit {
-		return fmt.Sprintf("%.0f B", n)
+func format(b float64, bin bool) string {
+	unit := float64(1000)
+	if bin {
+		unit = 1024
+	}
+	if b < unit {
+		return fmt.Sprintf("%.0f B", b)
 	} else {
-		e := math.Floor(math.Log(n) / math.Log(unit))
-		pfx := "KMGTPE"[uint8(e)-1]
-		return fmt.Sprintf("%.02f %c%s", n/math.Pow(unit, e), pfx, sfx)
+		exp := math.Floor(math.Log(b) / math.Log(unit))
+		pfx := new(bytes.Buffer)
+		pfx.WriteByte("KMGTPE"[uint8(exp)-1])
+		if bin {
+			pfx.WriteString("i")
+		}
+		return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, exp), pfx)
 	}
 }

+ 5 - 6
bytes/bytes_test.go

@@ -11,20 +11,19 @@ func TestFormat(t *testing.T) {
 
 	// MB
 	f = Format(13231323)
-	if f != "12.62 MB" {
-		t.Errorf("formatted bytes should be 12.62 MB, found %s", f)
+	if f != "13.23 MB" {
+		t.Errorf("formatted bytes should be 13.23 MB, found %s", f)
 	}
 
 	// Exact
-	f = Format(1024 * 1024 * 1024)
+	f = Format(1000 * 1000 * 1000)
 	if f != "1.00 GB" {
 		t.Errorf("formatted bytes should be 1.00 GB, found %s", f)
 	}
 }
 
-func TestBinaryPrefix(t *testing.T) {
-	BinaryPrefix(true)
-	f := Format(1323)
+func TestFormatBin(t *testing.T) {
+	f := FormatBin(1323)
 	if f != "1.29 KiB" {
 		t.Errorf("formatted bytes should be 1.29 KiB, found %s", f)
 	}