Skip to content

Commit

Permalink
Merge pull request #142 from rebuy-de/add-formatting
Browse files Browse the repository at this point in the history
Add functions for byte formatting
  • Loading branch information
der-eismann authored Feb 10, 2023
2 parents 66c2c25 + 58ac4f7 commit 09f0f2d
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
31 changes: 31 additions & 0 deletions pkg/formatutil/bytes.go
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])
}
34 changes: 34 additions & 0 deletions pkg/formatutil/bytes_test.go
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)
}
}
}

0 comments on commit 09f0f2d

Please sign in to comment.