Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HumanReadable: respect zero value input #46

Merged
merged 2 commits into from
Mar 14, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 7 additions & 0 deletions convert/bytes_common.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,20 @@ func ParseBytes(value string) (ByteAny, error) {
// Meant as a universal function to be used by the implementations, with base and a list of unit names.
//
// A special behavior is that resulting values smaller than 2 are displayed with the lower exponent.
// If the input value is 0, humanReadable will always return "0MB"
//
// Examples:
// 1073741824B -> 1000KB
// 2147483648B -> 2MB
// 0 -> 0MB
//
func humanReadable(b uint64, units []string, base float64) (float64, string) {
if b == 0 {
return 0, "MB"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for nitpicking, but why not B instead of MB? Small efficiency improvement at not cost and no doubt about rounding errors.

}

exponent := math.Log(float64(b)) / math.Log(base)

// Round to the unit scaled exponent
unitExponent := math.Floor(exponent)

Expand Down
1 change: 1 addition & 0 deletions convert/bytes_iec_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
)

func TestBytesIEC_HumanReadable(t *testing.T) {
assert.Equal(t, "0MB", BytesIEC(0).HumanReadable())
assert.Equal(t, "999B", BytesIEC(999).HumanReadable())
assert.Equal(t, "999KiB", BytesIEC(999*1024).HumanReadable())
assert.Equal(t, "999MiB", BytesIEC(999*1024*1024).HumanReadable())
Expand Down
1 change: 1 addition & 0 deletions convert/bytes_si_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
)

func TestBytesSI_HumanReadable(t *testing.T) {
assert.Equal(t, "0MB", BytesSI(0).HumanReadable())
assert.Equal(t, "999B", BytesSI(999).HumanReadable())
assert.Equal(t, "999KB", BytesSI(999*1000).HumanReadable())
assert.Equal(t, "999MB", BytesSI(999*1000*1000).HumanReadable())
Expand Down