clean up of the codebase
This commit is contained in:
1 parent
7822529a38
commit
0ac61b4ece
52 files changed
+2545
-2274
No files matched your search
@@ -0,0 +1,42 @@
|
||||
package units
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var StorageToken = regexp.MustCompile(`^([+-]?)(\d+(?:\.\d+)?)(tib|tb|t|gib|gb|g|mib|mb|m)$`)
|
||||
|
||||
func ParseSizeMB(s string) (int64, error) {
|
||||
t := strings.ToLower(strings.ReplaceAll(strings.TrimSpace(s), " ", ""))
|
||||
p := StorageToken.FindStringSubmatch(t)
|
||||
if p == nil || p[1] != "" {
|
||||
return 0, fmt.Errorf("%q isn't a size like 5G or 500M", s)
|
||||
}
|
||||
return ToMB(p[2], p[3]), nil
|
||||
}
|
||||
|
||||
func ToMB(num, unit string) int64 {
|
||||
n, _ := strconv.ParseFloat(num, 64)
|
||||
switch unit[0] {
|
||||
case 't':
|
||||
n *= 1024 * 1024
|
||||
case 'g':
|
||||
n *= 1024
|
||||
}
|
||||
return int64(math.Round(n))
|
||||
}
|
||||
|
||||
func FormatMB(mb int64) string {
|
||||
trim := func(f float64) string { return strconv.FormatFloat(math.Round(f*10)/10, 'f', -1, 64) }
|
||||
switch {
|
||||
case mb >= 1024*1024:
|
||||
return trim(float64(mb)/(1024*1024)) + " TB"
|
||||
case mb >= 1024:
|
||||
return trim(float64(mb)/1024) + " GB"
|
||||
}
|
||||
return fmt.Sprintf("%d MB", mb)
|
||||
}
|
||||
Reference in new issue
Block a user