Skip to content

Commit

Permalink
add: util for formatting bytes format
Browse files Browse the repository at this point in the history
  • Loading branch information
owlinux1000 committed Oct 1, 2023
1 parent 2afdd0f commit 86d31aa
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
19 changes: 19 additions & 0 deletions internal/util.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package internal

import (
"fmt"
)

// ref: https://yourbasic.org/golang/formatting-byte-size-to-human-readable-format/
func formatBytes(b int64) string {
const unit = 1000
if b < unit {
return fmt.Sprintf("%d", b)
}
div, exp := int64(unit), 0
for n := b / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f%c", float64(b)/float64(div), "KMGTPE"[exp])
}
19 changes: 19 additions & 0 deletions internal/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package internal

import "testing"

func TestFormatBytes(t *testing.T) {
tests := map[int64]string{
999: "999",
1024: "1.0K",
1536: "1.5K",
987654321: "987.7M",
}
for key, value := range tests {
got := formatBytes(key)
want := value
if got != want {
t.Fatalf("got: %v, want: %v\n", got, want)
}
}
}

0 comments on commit 86d31aa

Please sign in to comment.