@@ -2,8 +2,8 @@ package bytes
2
2
3
3
import (
4
4
"fmt"
5
- "regexp"
6
5
"strconv"
6
+ "unicode"
7
7
)
8
8
9
9
type (
@@ -22,8 +22,7 @@ const (
22
22
)
23
23
24
24
var (
25
- pattern = regexp .MustCompile (`(?i)^(-?\d+)([KMGTP]B?|B)$` )
26
- global = New ()
25
+ global = New ()
27
26
)
28
27
29
28
// New creates a Bytes instance.
@@ -43,9 +42,6 @@ func (*Bytes) Format(b int64) string {
43
42
case b < MB :
44
43
value /= KB
45
44
multiple = "KB"
46
- case b < MB :
47
- value /= KB
48
- multiple = "KB"
49
45
case b < GB :
50
46
value /= MB
51
47
multiple = "MB"
@@ -59,40 +55,39 @@ func (*Bytes) Format(b int64) string {
59
55
value /= PB
60
56
multiple = "PB"
61
57
}
62
-
63
- return fmt .Sprintf ("%.02f%s" , value , multiple )
58
+ return strconv .FormatFloat (value , 'f' , 2 , 64 ) + multiple
64
59
}
65
60
66
61
// Parse parses human readable bytes string to bytes integer.
67
62
// For example, 6GB (6G is also valid) will return 6442450944.
68
- func (* Bytes ) Parse (value string ) (i int64 , err error ) {
69
- parts := pattern .FindStringSubmatch (value )
70
- if len (parts ) < 3 {
71
- return 0 , fmt .Errorf ("error parsing value=%s" , value )
72
- }
73
- bytesString := parts [1 ]
74
- multiple := parts [2 ]
75
- bytes , err := strconv .ParseInt (bytesString , 10 , 64 )
76
- if err != nil {
77
- return
78
- }
63
+ func (* Bytes ) Parse (value string ) (int64 , error ) {
64
+ for i , s := range value {
65
+ if unicode .IsLetter (s ) {
66
+ bytesString , multiple := value [:i ], value [i :]
67
+
68
+ bytes , err := strconv .ParseInt (bytesString , 10 , 64 )
69
+ if err != nil {
70
+ return 0 , err
71
+ }
79
72
80
- switch multiple {
81
- case "B" :
82
- return bytes * B , nil
83
- case "K" , "KB" :
84
- return bytes * KB , nil
85
- case "M" , "MB" :
86
- return bytes * MB , nil
87
- case "G" , "GB" :
88
- return bytes * GB , nil
89
- case "T" , "TB" :
90
- return bytes * TB , nil
91
- case "P" , "PB" :
92
- return bytes * PB , nil
73
+ switch multiple {
74
+ case "B" :
75
+ return bytes * B , nil
76
+ case "K" , "KB" :
77
+ return bytes * KB , nil
78
+ case "M" , "MB" :
79
+ return bytes * MB , nil
80
+ case "G" , "GB" :
81
+ return bytes * GB , nil
82
+ case "T" , "TB" :
83
+ return bytes * TB , nil
84
+ case "P" , "PB" :
85
+ return bytes * PB , nil
86
+ }
87
+ }
93
88
}
94
89
95
- return
90
+ return 0 , fmt . Errorf ( "error parsing value=%s" , value )
96
91
}
97
92
98
93
// Format wraps global Bytes's Format function.
0 commit comments