-
Notifications
You must be signed in to change notification settings - Fork 9
/
util.go
90 lines (79 loc) · 1.25 KB
/
util.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
89
90
package configuration
import (
"errors"
"regexp"
"strconv"
"strings"
)
var sizeRe = regexp.MustCompile(`([1-9]\d*)([kmgtKMGT]?[i]?[bB])`)
func ParseSizeString(s string) (int64, error) {
if s == "" || s == "0" {
return 0, nil
}
const (
k = 1000
ki = 1024
)
parts := sizeRe.FindStringSubmatch(s)
if len(parts) != 3 {
return 0, errors.New("invalid size")
}
ns := parts[1]
units := parts[2]
n, err := strconv.ParseInt(ns, 10, 64)
if err != nil {
return 0, err
}
var (
mult int64 = 1
usingBits = false
)
switch len(units) {
case 1:
if units[0] == 'b' {
usingBits = true
}
case 2:
if units[1] == 'b' {
usingBits = true
}
order := strings.ToLower(string(units[0]))
switch order {
case "k":
mult = k
case "m":
mult = k * k
case "g":
mult = k * k * k
case "t":
mult = k * k * k * k
}
case 3:
if units[2] == 'b' {
usingBits = true
}
order := strings.ToLower(string(units[0]))
switch order {
case "k":
mult = ki
case "m":
mult = ki * ki
case "g":
mult = ki * ki * ki
case "t":
mult = ki * ki * ki * ki
}
}
if usingBits {
if 1 < mult {
mult /= 8
} else {
bumpByOne := n%8 != 0
n /= 8
if bumpByOne {
n += 1
}
}
}
return mult * n, nil
}