45 lines
927 B
Go
45 lines
927 B
Go
//go:build linux || freebsd
|
|
// +build linux freebsd
|
|
|
|
package format
|
|
|
|
import "fmt"
|
|
|
|
// Bytes formats byte count as human-readable string (DECIMAL units: KB=1000)
|
|
func Bytes(b int64) string {
|
|
const unit = 1000
|
|
if b < 0 {
|
|
return "? B"
|
|
}
|
|
if b < unit {
|
|
return fmt.Sprintf("%d B", b)
|
|
}
|
|
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
|
|
value := float64(b)
|
|
exp := 0
|
|
for value >= unit && exp < len(units)-1 {
|
|
value /= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.1f %s", value, units[exp])
|
|
}
|
|
|
|
// Speed formats speed as human-readable string (DECIMAL units)
|
|
func Speed(speed float64) string {
|
|
const unit = 1000
|
|
if speed < 0 {
|
|
return "? B/s"
|
|
}
|
|
if speed < unit {
|
|
return fmt.Sprintf("%.1f B/s", speed)
|
|
}
|
|
units := []string{"B/s", "KB/s", "MB/s", "GB/s", "TB/s", "PB/s"}
|
|
value := speed
|
|
exp := 0
|
|
for value >= unit && exp < len(units)-1 {
|
|
value /= unit
|
|
exp++
|
|
}
|
|
return fmt.Sprintf("%.1f %s", value, units[exp])
|
|
}
|