-
Notifications
You must be signed in to change notification settings - Fork 26
/
size.go
88 lines (75 loc) · 1.54 KB
/
size.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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package runner
import (
"fmt"
"strconv"
)
// Size stores number of byte for the object. E.g. Memory.
// Maximum size is bounded by 64-bit limit
type Size uint64
// String stringer interface for print
func (s Size) String() string {
t := uint64(s)
switch {
case t < 1<<10:
return fmt.Sprintf("%d B", t)
case t < 1<<20:
return fmt.Sprintf("%.1f KiB", float64(t)/float64(1<<10))
case t < 1<<30:
return fmt.Sprintf("%.1f MiB", float64(t)/float64(1<<20))
default:
return fmt.Sprintf("%.1f GiB", float64(t)/float64(1<<30))
}
}
// Set parse the size value from string
func (s *Size) Set(str string) error {
switch str[len(str)-1] {
case 'b', 'B':
str = str[:len(str)-1]
}
factor := 0
switch str[len(str)-1] {
case 'k', 'K':
factor = 10
str = str[:len(str)-1]
case 'm', 'M':
factor = 20
str = str[:len(str)-1]
case 'g', 'G':
factor = 30
str = str[:len(str)-1]
}
t, err := strconv.Atoi(str)
if err != nil {
return err
}
*s = Size(t << factor)
return nil
}
// Byte return size in bytes
func (s Size) Byte() uint64 {
return uint64(s)
}
// KiB return size in KiB
func (s Size) KiB() uint64 {
return uint64(s) >> 10
}
// MiB return size in MiB
func (s Size) MiB() uint64 {
return uint64(s) >> 20
}
// GiB return size in GiB
func (s Size) GiB() uint64 {
return uint64(s) >> 30
}
// TiB return size in TiB
func (s Size) TiB() uint64 {
return uint64(s) >> 40
}
// PiB return size in PiB
func (s Size) PiB() uint64 {
return uint64(s) >> 50
}
// EiB return size in EiB
func (s Size) EiB() uint64 {
return uint64(s) >> 60
}