forked from sneak/util
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
39 lines
961 B
Go
39 lines
961 B
Go
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])
|
|
}
|