1
0
forked from sneak/util

add HumanBytes for printing a byte count readably

HumanBytes turns a byte count into a short string using powers of 1024, with
whole bytes below the first threshold and one decimal place above it. Comes
with a doc comment and table-driven tests. (closes #11)

Model: opus-5
This commit is contained in:
2026-09-05 03:27:53 +00:00
parent 9302c14a6c
commit 500768ad32
2 changed files with 71 additions and 0 deletions

38
humanbytes.go Normal file
View File

@@ -0,0 +1,38 @@
package util
import (
"fmt"
"math"
)
const bytesPerUnit = 1024
var byteUnits = []string{"KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
// HumanBytes writes a byte count the way a person would read it, using powers
// of 1024: "0 B", "1023 B", "1.0 KiB", "1.5 MiB", "16.0 EiB". Counts below 1024
// are given as whole bytes, and anything larger gets one digit after the
// decimal point.
func HumanBytes(bytes uint64) string {
if bytes < bytesPerUnit {
return fmt.Sprintf("%d B", bytes)
}
value := float64(bytes)
unit := -1
for value >= bytesPerUnit && unit < len(byteUnits)-1 {
value /= bytesPerUnit
unit++
}
// Rounding happens after the unit has been chosen, so a count just short
// of the next threshold would otherwise come out as "1024.0 KiB" rather
// than "1.0 MiB".
if unit < len(byteUnits)-1 && math.Round(value*10)/10 >= bytesPerUnit {
value /= bytesPerUnit
unit++
}
return fmt.Sprintf("%.1f %s", value, byteUnits[unit])
}