Repository navigation
Expand file tree
/
Copy pathbytesize.go
More file actions
85 lines (74 loc) · 1.54 KB
/
Copy pathbytesize.go
File metadata and controls
85 lines (74 loc) · 1.54 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
// Copyright 2016 CodisLabs. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package bytesize
import (
"regexp"
"strconv"
"strings"
"github.com/CodisLabs/codis/pkg/utils/errors"
"github.com/CodisLabs/codis/pkg/utils/log"
)
const (
B = 1 << (10 * iota)
KB
MB
GB
TB
PB
)
var (
BytesizeRegexp = regexp.MustCompile(`(?i)^\s*(\-?[\d\.]+)\s*([KMGTP]?B|[BKMGTP]|)\s*$`)
digitsRegexp = regexp.MustCompile(`^\-?\d+$`)
)
var (
ErrBadBytesize = errors.New("invalid byte size")
ErrBadBytesizeUnit = errors.New("invalid byte size unit")
)
func Parse(s string) (int64, error) {
if !BytesizeRegexp.MatchString(s) {
return 0, errors.Trace(ErrBadBytesize)
}
subs := BytesizeRegexp.FindStringSubmatch(s)
if len(subs) != 3 {
return 0, errors.Trace(ErrBadBytesize)
}
size := int64(0)
switch strings.ToUpper(string(subs[2])) {
case "B", "":
size = 1
case "KB", "K":
size = KB
case "MB", "M":
size = MB
case "GB", "G":
size = GB
case "TB", "T":
size = TB
case "PB", "P":
size = PB
default:
return 0, errors.Trace(ErrBadBytesizeUnit)
}
text := subs[1]
if digitsRegexp.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
}