-
Notifications
You must be signed in to change notification settings - Fork 6
/
size.go
99 lines (81 loc) · 2.01 KB
/
size.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
97
98
99
package gox
import (
"strconv"
"strings"
"unsafe"
"github.com/goexl/gox/internal/constant"
)
const (
SizeB Size = 1
SizeKB = 1024 * SizeB
SizeMB = 1024 * SizeKB
SizeGB = 1024 * SizeMB
SizeTB = 1024 * SizeGB
SizePB = 1024 * SizeTB
SizeEB = 1024 * SizePB
)
var _ = ParseSize
// Size 字节大小
type Size int64
// ParseSize 解析字节大小
func ParseSize(from string) (size Size, err error) {
// 逐步解析各个容量
for _, volume := range strings.Split(from, constant.Space) {
var unit, num string
length := len(volume)
check := volume[length-2]
if '0' <= check && '9' >= check { // 如果倒数第二位是数字,表示是以最小单位
unit = volume[length-1:]
num = volume[:length-1]
} else { // 表示是形如KB,MB,GB等单位
unit = volume[length-2:]
num = volume[:length-2]
}
// 计算数字大小
var capacity float64
if capacity, err = strconv.ParseFloat(num, constant.Float64Size); nil != err {
return
}
switch strings.ToLower(unit) {
case "b":
size += Size(capacity)
case "kb", "k":
size += Size(capacity) * SizeKB
case "mb", "m":
size += Size(capacity) * SizeMB
case "gb", "g":
size += Size(capacity) * SizeGB
case "tb", "t":
size += Size(capacity) * SizeTB
case "pb", "p":
size += Size(capacity) * SizePB
case "eb", "e":
size += Size(capacity) * SizeEB
}
}
return
}
func (s *Size) String() string {
return s.Formatter().Format()
}
func (s *Size) Bit() int64 {
return int64(*s) * 8
}
func (s *Size) Byte() int64 {
return int64(*s)
}
func (s *Size) Bit32() int32 {
return int32(*s) * 8
}
func (s *Size) Formatter() *sizeFormatter {
return newSizeFormatter(s)
}
func (s Size) MarshalJSON() (bytes []byte, err error) {
bytes = StringBuilder(constant.Quote, s.String(), constant.Quote).Bytes()
return
}
func (s *Size) UnmarshalJSON(bytes []byte) (err error) {
json := *(*string)(unsafe.Pointer(&bytes))
*s, err = ParseSize(strings.ReplaceAll(json, constant.Quote, constant.Empty))
return
}