-
Notifications
You must be signed in to change notification settings - Fork 0
/
json.go
52 lines (39 loc) · 845 Bytes
/
json.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
package typeutil
import (
"encoding/json"
"fmt"
"math"
"time"
)
type JSONDuration struct {
time.Duration
}
func (j JSONDuration) MarshalJSON() ([]byte, error) {
return json.Marshal(j.Duration.String())
}
type JSONBytes struct {
Size int64
}
func (j JSONBytes) MarshalJSON() ([]byte, error) {
return json.Marshal(j.String())
}
func (j JSONBytes) String() string {
var (
pre = []string{"B", "KiB", "MiB", "GiB", "TiB"}
bits = math.Log2(float64(j.Size))
pos = math.Floor(bits / 10)
exp = math.Pow(1024, float64(pos))
short = float64(j.Size) / exp
sufix = pre[int(pos)]
)
if pos == 0 {
return fmt.Sprintf("%.0f%s", short, sufix)
}
if short < 10 {
return fmt.Sprintf("%.3f%s", short, sufix)
}
if short < 100 {
return fmt.Sprintf("%.2f%s", short, sufix)
}
return fmt.Sprintf("%.1f%s", short, sufix)
}