2017-02-26 22:04:24 +00:00
|
|
|
package cwidgets
|
2017-01-06 02:01:57 +00:00
|
|
|
|
|
|
|
import (
|
2017-01-06 11:51:11 +00:00
|
|
|
"strconv"
|
2017-01-06 02:01:57 +00:00
|
|
|
)
|
|
|
|
|
2017-01-06 11:51:11 +00:00
|
|
|
const (
|
2020-10-25 14:08:06 +00:00
|
|
|
// byte ratio constants
|
|
|
|
_ = iota
|
|
|
|
kib float64 = 1 << (10 * iota)
|
|
|
|
mib
|
|
|
|
gib
|
|
|
|
tib
|
|
|
|
pib
|
2017-01-06 11:51:11 +00:00
|
|
|
)
|
|
|
|
|
2020-10-25 14:08:06 +00:00
|
|
|
var (
|
|
|
|
units = []float64{
|
|
|
|
1,
|
|
|
|
kib,
|
|
|
|
mib,
|
|
|
|
gib,
|
|
|
|
tib,
|
|
|
|
pib,
|
|
|
|
}
|
2017-01-08 16:13:25 +00:00
|
|
|
|
2020-10-25 14:08:06 +00:00
|
|
|
// short, full unit labels
|
|
|
|
labels = [][2]string{
|
|
|
|
[2]string{"B", "B"},
|
|
|
|
[2]string{"K", "KiB"},
|
|
|
|
[2]string{"M", "MiB"},
|
|
|
|
[2]string{"G", "GiB"},
|
|
|
|
[2]string{"T", "TiB"},
|
|
|
|
[2]string{"P", "PiB"},
|
2017-01-06 11:51:11 +00:00
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
|
|
|
|
// maximum displayed precision per unit
|
|
|
|
maxPrecision = []int{
|
|
|
|
0, // B
|
|
|
|
0, // kib
|
|
|
|
1, // mib
|
|
|
|
1, // gib
|
|
|
|
2, // tib
|
|
|
|
2, // pib
|
2017-01-06 11:51:11 +00:00
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
// convenience methods
|
|
|
|
func ByteFormat(n int) string { return byteFormat(float64(n), false) }
|
|
|
|
func ByteFormatShort(n int) string { return byteFormat(float64(n), true) }
|
|
|
|
func ByteFormat64(n int64) string { return byteFormat(float64(n), false) }
|
|
|
|
func ByteFormat64Short(n int64) string { return byteFormat(float64(n), true) }
|
|
|
|
|
|
|
|
func byteFormat(n float64, short bool) string {
|
|
|
|
i := len(units) - 1
|
|
|
|
|
|
|
|
for i > 0 {
|
|
|
|
if n >= units[i] {
|
|
|
|
n /= units[i]
|
|
|
|
break
|
|
|
|
}
|
|
|
|
i--
|
2017-01-06 11:51:11 +00:00
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
|
|
|
|
if short {
|
|
|
|
return unpadFloat(n, maxPrecision[i]) + labels[i][0]
|
2017-06-09 17:14:27 +00:00
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
return unpadFloat(n, maxPrecision[i]) + labels[i][1]
|
2017-01-20 15:56:49 +00:00
|
|
|
}
|
|
|
|
|
2020-10-25 14:08:06 +00:00
|
|
|
func unpadFloat(f float64, maxp int) string {
|
|
|
|
return strconv.FormatFloat(f, 'f', getPrecision(f, maxp), 64)
|
2017-01-20 15:56:49 +00:00
|
|
|
}
|
|
|
|
|
2020-10-25 14:08:06 +00:00
|
|
|
func getPrecision(f float64, maxp int) int {
|
2017-01-20 15:56:49 +00:00
|
|
|
frac := int((f - float64(int(f))) * 100)
|
2020-10-25 14:08:06 +00:00
|
|
|
if frac == 0 || maxp == 0 {
|
2017-01-20 15:56:49 +00:00
|
|
|
return 0
|
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
if frac%10 == 0 || maxp < 2 {
|
2017-01-20 15:56:49 +00:00
|
|
|
return 1
|
|
|
|
}
|
2020-10-25 14:08:06 +00:00
|
|
|
return maxp
|
2017-01-06 11:51:11 +00:00
|
|
|
}
|