1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94
|
package counts
import (
"fmt"
)
// A quantity that can be made human-readable using Human().
type Humanable interface {
// Return the value as a uint64, and a boolean telling whether it
// overflowed.
ToUint64() (uint64, bool)
}
// An object that can format a Humanable in human-readable format.
type Humaner struct {
name string
prefixes []Prefix
}
type Prefix struct {
Name string
Multiplier uint64
}
var Metric = Humaner{
name: "metric",
prefixes: []Prefix{
{"", 1},
{"k", 1e3},
{"M", 1e6},
{"G", 1e9},
{"T", 1e12},
{"P", 1e15},
},
}
var Binary = Humaner{
name: "binary",
prefixes: []Prefix{
{"", 1 << (10 * 0)},
{"Ki", 1 << (10 * 1)},
{"Mi", 1 << (10 * 2)},
{"Gi", 1 << (10 * 3)},
{"Ti", 1 << (10 * 4)},
{"Pi", 1 << (10 * 5)},
},
}
func (h *Humaner) Name() string {
return h.name
}
// Format n, aligned, in `len(unit) + 10` or fewer characters (except
// for extremely large numbers).
func (h *Humaner) FormatNumber(n uint64, unit string) (string, string) {
prefix := h.prefixes[0]
wholePart := n
for _, p := range h.prefixes {
w := n / p.Multiplier
if w >= 1 {
wholePart = w
prefix = p
}
}
if prefix.Multiplier == 1 {
return fmt.Sprintf("%d", n), unit
} else {
mantissa := float64(n) / float64(prefix.Multiplier)
var format string
if wholePart >= 100 {
// `mantissa` can actually be up to 1023.999.
format = "%.0f"
} else if wholePart >= 10 {
format = "%.1f"
} else {
format = "%.2f"
}
return fmt.Sprintf(format, mantissa), prefix.Name + unit
}
}
// Format values, aligned, in `len(unit) + 10` or fewer characters
// (except for extremely large numbers).
func (h *Humaner) Format(value Humanable, unit string) (string, string) {
n, overflow := value.ToUint64()
if overflow {
return "∞", unit
}
return h.FormatNumber(n, unit)
}
|