Repository navigation
Expand file tree
/
Copy pathbytesize.go
More file actions
134 lines (117 loc) · 2.4 KB
/
Copy pathbytesize.go
File metadata and controls
134 lines (117 loc) · 2.4 KB
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Copyright 2016 CodisLabs. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package bytesize
import (
"fmt"
"regexp"
"strconv"
"github.com/CodisLabs/codis/pkg/utils/errors"
"github.com/CodisLabs/codis/pkg/utils/log"
)
const (
_ = 1 << (10 * iota)
KB
MB
GB
TB
PB
)
type Int64 int64
func (b Int64) Int64() int64 {
return int64(b)
}
func (b Int64) AsInt() int {
return int(b)
}
func (b Int64) MarshalText() ([]byte, error) {
if b == 0 {
return []byte("0"), nil
}
var abs = int64(b)
if abs < 0 {
abs = -abs
}
switch {
case abs%PB == 0:
val := b.Int64() / PB
return []byte(fmt.Sprintf("%dpb", val)), nil
case abs%TB == 0:
val := b.Int64() / TB
return []byte(fmt.Sprintf("%dtb", val)), nil
case abs%GB == 0:
val := b.Int64() / GB
return []byte(fmt.Sprintf("%dgb", val)), nil
case abs%MB == 0:
val := b.Int64() / MB
return []byte(fmt.Sprintf("%dmb", val)), nil
case abs%KB == 0:
val := b.Int64() / KB
return []byte(fmt.Sprintf("%dkb", val)), nil
default:
return []byte(fmt.Sprintf("%d", b.Int64())), nil
}
}
func (p *Int64) UnmarshalText(text []byte) error {
n, err := Parse(string(text))
if err != nil {
return err
}
*p = Int64(n)
return nil
}
var (
fullRegexp = regexp.MustCompile(`^\s*(\-?[\d\.]+)\s*([kmgtp]?b|[bkmgtp]|)\s*$`)
digitsOnly = regexp.MustCompile(`^\-?\d+$`)
)
var (
ErrBadByteSize = errors.New("invalid bytesize")
ErrBadByteSizeUnit = errors.New("invalid bytesize unit")
)
func Parse(s string) (int64, error) {
if !fullRegexp.MatchString(s) {
return 0, errors.Trace(ErrBadByteSize)
}
subs := fullRegexp.FindStringSubmatch(s)
if len(subs) != 3 {
return 0, errors.Trace(ErrBadByteSize)
}
text := subs[1]
unit := subs[2]
size := int64(1)
switch unit {
case "b", "":
case "k", "kb":
size = KB
case "m", "mb":
size = MB
case "g", "gb":
size = GB
case "t", "tb":
size = TB
case "p", "pb":
size = PB
default:
return 0, errors.Trace(ErrBadByteSizeUnit)
}
if digitsOnly.MatchString(text) {
n, err := strconv.ParseInt(text, 10, 64)
if err != nil {
return 0, errors.Trace(ErrBadByteSize)
}
size *= n
} else {
n, err := strconv.ParseFloat(text, 64)
if err != nil {
return 0, errors.Trace(ErrBadByteSize)
}
size = int64(float64(size) * n)
}
return size, nil
}
func MustParse(s string) int64 {
v, err := Parse(s)
if err != nil {
log.PanicError(err, "parse bytesize failed")
}
return v
}