-
Notifications
You must be signed in to change notification settings - Fork 0
/
encoding.go
73 lines (61 loc) · 1.38 KB
/
encoding.go
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
package encoding
import "strconv"
func label(value float64, unit unit_measure) string {
var prec int
if unit.factor != 1 {
prec = 2
value *= unit.factor
}
return strconv.FormatFloat(value, 'f', prec, 64) + unit.name
}
func scale(value float64, units []unit_measure) string {
var unit unit_measure
for _, unit = range units {
if unit.factor * value < 1000 {
break
}
}
return label(value, unit)
}
type Cardinal float64
func (c Cardinal) String() string {
units := []unit_measure{
{1, ""},
{1e-3, " thousand"},
{1e-6, " million"},
{1e-9, " billion"},
{1e-12, " trillion"},
}
return scale(float64(c), units)
}
type Percent float64
func (p Percent) String() string {
unit := unit_measure{100, " %"}
return label(float64(p), unit)
}
type Rate float64
func (r Rate) String() string {
units := []unit_measure{
{1, " byte/s"},
{1e-3, " kilobyte/s"},
{1e-6, " megabyte/s"},
{1e-9, " gigabyte/s"},
{1e-12, " terabyte/s"},
}
return scale(float64(r), units)
}
type Size float64
func (s Size) String() string {
units := []unit_measure{
{1, " byte"},
{1e-3, " kilobyte"},
{1e-6, " megabyte"},
{1e-9, " gigabyte"},
{1e-12, " terabyte"},
}
return scale(float64(s), units)
}
type unit_measure struct {
factor float64
name string
}