-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add: util for formatting bytes format
- Loading branch information
1 parent
2afdd0f
commit 86d31aa
Showing
2 changed files
with
38 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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]) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} | ||
} | ||
} |