Skip to content

Commit 2219395

Browse files
committed
Saving some bytes
Signed-off-by: Vishal Rana <[email protected]>
1 parent 60ec6a7 commit 2219395

File tree

2 files changed

+8
-8
lines changed

2 files changed

+8
-8
lines changed

bytes/bytes.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
package bytes
22

33
import (
4-
"bytes"
54
"fmt"
65
"math"
76
)
@@ -26,12 +25,13 @@ func format(b float64, bin bool) string {
2625
if b < unit {
2726
return fmt.Sprintf("%.0f B", b)
2827
} else {
29-
exp := math.Floor(math.Log(b) / math.Log(unit))
30-
pfx := new(bytes.Buffer)
31-
pfx.WriteByte("KMGTPE"[uint8(exp)-1])
28+
i := uint8(math.Floor(math.Log(b) / math.Log(unit)))
29+
pre := make([]byte, 1, 2)
30+
pre[0] = "KMGTPE"[i-1]
3231
if bin {
33-
pfx.WriteString("i")
32+
pre = pre[:2]
33+
pre[1] = 'i'
3434
}
35-
return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, exp), pfx)
35+
return fmt.Sprintf("%.02f %sB", b/math.Pow(unit, i), pre)
3636
}
3737
}

bytes/bytes_test.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ func TestFormat(t *testing.T) {
1818
// Exact
1919
f = Format(1000 * 1000 * 1000)
2020
if f != "1.00 GB" {
21-
t.Errorf("formatted bytes should be 1.00 GB, found %s", f)
21+
t.Errorf("formatted bytes should be 1.00 GB, found %s xxx", f)
2222
}
2323
}
2424

2525
func TestFormatB(t *testing.T) {
2626
f := FormatB(1323)
2727
if f != "1.29 KiB" {
28-
t.Errorf("formatted bytes should be 1.29 KiB, found %s", f)
28+
t.Errorf("formatted bytes should be 1.29 KiB, found %s xxx", f)
2929
}
3030
}

0 commit comments

Comments
 (0)