-
Notifications
You must be signed in to change notification settings - Fork 1
/
chunksize.go
78 lines (71 loc) · 1.27 KB
/
chunksize.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
package main
import "strconv"
const (
K = 1024
M = 1024 * 1024
G = 1024 * 1024 * 1024
)
type ChunkSize int64
func (c *ChunkSize) MarshalText() (text []byte, err error) { // nolint: unparam
return []byte(c.String()), nil
}
func (c *ChunkSize) UnmarshalText(text []byte) error {
return c.Set(string(text))
}
func (c *ChunkSize) Set(value string) error {
switch value[len(value)-1] {
case 'K':
value = value[:len(value)-1]
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
i *= K
*c = ChunkSize(i)
return nil
case 'M':
value = value[:len(value)-1]
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
i *= M
*c = ChunkSize(i)
return nil
case 'G':
value = value[:len(value)-1]
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
i *= G
*c = ChunkSize(i)
return nil
default:
i, err := strconv.ParseInt(value, 10, 64)
if err != nil {
return err
}
*c = ChunkSize(i)
return nil
}
}
func (c *ChunkSize) String() string {
i := int64(*c)
if i == 0 {
return "0"
}
var postfix string
switch {
case i%G == 0:
i /= G
postfix = "G"
case i%M == 0:
i /= M
postfix = "M"
case i%K == 0:
i /= K
postfix = "K"
}
return strconv.FormatInt(i, 10) + postfix
}