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 95 96 97 98 99 100 101 102 103 104 105
|
package counts
import (
"fmt"
)
// Humanable is a quantity that can be made human-readable using
// `Humaner.Format()`.
type Humanable interface {
// ToUint64 returns the value as a uint64, and a boolean telling
// whether it overflowed.
ToUint64() (uint64, bool)
}
// Humaner is an object that can format a Humanable in human-readable
// format.
type Humaner struct {
name string
prefixes []Prefix
}
// Prefix is a metric-like prefix that implies a scaling factor.
type Prefix struct {
Name string
Multiplier uint64
}
// Metric is a Humaner representing metric prefixes.
var Metric = Humaner{
name: "metric",
prefixes: []Prefix{
{"", 1},
{"k", 1e3},
{"M", 1e6},
{"G", 1e9},
{"T", 1e12},
{"P", 1e15},
},
}
// Binary is a Humaner representing power-of-1024 based prefixes,
// typically used for bytes.
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)},
},
}
// Name returns the name of `h` ("metric" or "binary").
func (h *Humaner) Name() string {
return h.name
}
// FormatNumber formats n, aligned, in `len(unit) + 10` or fewer
// characters (except for extremely large numbers). It returns strings
// representing the numeral and the unit string.
func (h *Humaner) FormatNumber(n uint64, unit string) (numeral string, unitString 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
}
mantissa := float64(n) / float64(prefix.Multiplier)
var format string
switch {
case wholePart >= 100:
// `mantissa` can actually be up to 1023.999.
format = "%.0f"
case wholePart >= 10:
format = "%.1f"
default:
format = "%.2f"
}
return fmt.Sprintf(format, mantissa), prefix.Name + unit
}
// Format formats values, aligned, in `len(unit) + 10` or fewer
// characters (except for extremely large numbers). It returns strings
// representing the numeral and the unit string.
func (h *Humaner) Format(value Humanable, unit string) (numeral string, unitString string) {
n, overflow := value.ToUint64()
if overflow {
return "∞", unit
}
return h.FormatNumber(n, unit)
}
|