forked from docker-archive/runc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
units.go
96 lines (82 loc) · 1.58 KB
/
units.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
91
92
93
94
95
96
package units
import (
"fmt"
"strconv"
"strings"
)
func RAMInBytes(val string) (int64, error) {
if val == "-1" {
return -1, nil
}
num, sfx, found := strings.Cut(val, " ")
if !found {
// No space between the number and the suffix.
sep := strings.LastIndexAny(val, "01234567890.")
if sep == -1 {
// There should be at least a digit.
return -1, fmt.Errorf("invalid value: %q", val)
}
num = val[:sep+1]
sfx = val[sep+1:]
}
size, err := strconv.ParseFloat(num, 64)
if err != nil {
return -1, err
}
// Backward compatibility: reject negative sizes.
if size < 0 {
return -1, fmt.Errorf("invalid value: %q", val)
}
if len(sfx) == 0 {
return int64(size), nil
}
// Process the suffix.
if len(sfx) > 3 { // Too long.
goto badSuffix
}
sfx = strings.ToLower(sfx)
// Trivial case: b suffix.
if sfx[0] == 'b' {
if len(sfx) > 1 { // no extra characters allowed after b.
goto badSuffix
}
return int64(size), nil
}
if mul := getMultiplier(sfx[0]); mul != 0 {
size *= float64(mul)
} else {
goto badSuffix
}
// The suffix may have extra "b" or "ib" (e.g. KiB or MB).
switch {
case len(sfx) == 2 && sfx[1] != 'b':
goto badSuffix
case len(sfx) == 3 && sfx[1:] != "ib":
goto badSuffix
}
return int64(size), nil
badSuffix:
return -1, fmt.Errorf("invalid suffix: '%s'", sfx)
}
const (
kb = 1024
mb = 1024 * kb
gb = 1024 * mb
tb = 1024 * gb
pb = 1024 * tb
)
func getMultiplier(suffix byte) int64 {
switch suffix {
case 'k':
return kb
case 'm':
return mb
case 'g':
return gb
case 't':
return tb
case 'p':
return pb
}
return 0
}