-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #142 from rebuy-de/add-formatting
Add functions for byte formatting
- Loading branch information
Showing
2 changed files
with
65 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,31 @@ | ||
package formatutil | ||
|
||
import "fmt" | ||
|
||
func ByteFormatSI(b int64) string { | ||
const unit = 1000 | ||
if b < unit { | ||
return fmt.Sprintf("%d B", b) | ||
} | ||
div, exp := int64(unit), 0 | ||
for n := b / unit; n >= unit; n /= unit { | ||
div *= unit | ||
exp++ | ||
} | ||
return fmt.Sprintf("%.1f %cB", | ||
float64(b)/float64(div), "kMGTPE"[exp]) | ||
} | ||
|
||
func ByteFormatIEC(b int64) string { | ||
const unit = 1024 | ||
if b < unit { | ||
return fmt.Sprintf("%d B", b) | ||
} | ||
div, exp := int64(unit), 0 | ||
for n := b / unit; n >= unit; n /= unit { | ||
div *= unit | ||
exp++ | ||
} | ||
return fmt.Sprintf("%.1f %ciB", | ||
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,34 @@ | ||
package formatutil | ||
|
||
import "testing" | ||
|
||
type testCaseByteFormatter struct { | ||
input int64 | ||
expected string | ||
} | ||
|
||
func TestByteFormatting(t *testing.T) { | ||
casesIEC := []testCaseByteFormatter{ | ||
{16516, "16.1 KiB"}, | ||
{46564534534, "43.4 GiB"}, | ||
{9845345734653745, "8.7 PiB"}, | ||
} | ||
|
||
for _, testcase := range casesIEC { | ||
if output := ByteFormatIEC(testcase.input); output != testcase.expected { | ||
t.Errorf("Output %q not equal to expected %q", output, testcase.expected) | ||
} | ||
} | ||
|
||
casesSI := []testCaseByteFormatter{ | ||
{16516, "16.5 kB"}, | ||
{46564534534, "46.6 GB"}, | ||
{9845345734653745, "9.8 PB"}, | ||
} | ||
|
||
for _, testcase := range casesSI { | ||
if output := ByteFormatSI(testcase.input); output != testcase.expected { | ||
t.Errorf("Output %q not equal to expected %q", output, testcase.expected) | ||
} | ||
} | ||
} |