Selaa lähdekoodia

Bytes package to format bytes :star:

Vishal Rana 10 vuotta sitten
vanhempi
commit
80cefd19e2
3 muutettua tiedostoa jossa 101 lisäystä ja 0 poistoa
  1. 26 0
      bytes/README.md
  2. 33 0
      bytes/bytes.go
  3. 42 0
      bytes/bytes_test.go

+ 26 - 0
bytes/README.md

@@ -0,0 +1,26 @@
+# Bytes
+
+Format bytes
+
+## Installation
+
+```go get github.com/labstack/gommon/color```
+
+## [Usage](https://github.com/labstack/gommon/blob/master/bytes/bytes_test.go)
+
+### Decimal prefix
+
+```go
+fmt.Println(bytes.Format(1323))
+```
+
+`1.29 KB`
+
+### Binary prefix
+
+```go
+bytes.BinaryPrefix(true)
+fmt.Println(bytes.Format(1323))
+```
+
+`1.29 KiB`

+ 33 - 0
bytes/bytes.go

@@ -0,0 +1,33 @@
+package bytes
+
+import (
+	"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"
+	}
+}
+
+// Bytes formats bytes into string. For example, 1024 returns 1 KB
+func Format(b uint64) string {
+	n := float64(b)
+	unit := float64(1024)
+
+	if n == 0 {
+		return "--"
+	} else if n < unit {
+		return fmt.Sprintf("%.0f B", n)
+	} 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)
+	}
+}

+ 42 - 0
bytes/bytes_test.go

@@ -0,0 +1,42 @@
+package bytes
+
+import (
+	"testing"
+	"github.com/labstack/gommon/bytes"
+	"fmt"
+)
+
+func TestFormat(t *testing.T) {
+	fmt.Println(bytes.Format(1323))
+	// Zero
+	f := Format(0)
+	if f != "--" {
+		t.Errorf("formatted bytes should be --, found %s", f)
+	}
+
+	// B
+	f = Format(515)
+	if f != "515 B" {
+		t.Errorf("formatted bytes should be 515 B, found %s", f)
+	}
+
+	// MB
+	f = Format(13231323)
+	if f != "12.62 MB" {
+		t.Errorf("formatted bytes should be 12.62 MB, found %s", f)
+	}
+
+	// Exact
+	f = Format(1024 * 1024 * 1024)
+	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)
+	if f != "1.29 KiB" {
+		t.Errorf("formatted bytes should be 1.29 KiB, found %s", f)
+	}
+}