wheat-cache/pkg/util/memory.go

32 lines
728 B
Go
Raw Normal View History

2021-09-27 11:29:47 +08:00
package util
import (
"regexp"
"strconv"
"strings"
2021-10-25 11:08:18 +08:00
"gitee.com/timedb/wheatCache/pkg/errorx"
2021-09-27 11:29:47 +08:00
)
// ParseSizeToBit
// 支持MB, GB, KB, 格式 "5KB" 或者 "5kb"等等
2021-10-04 20:33:38 +08:00
func ParseSizeToBit(size string) (int64, error) {
2021-09-27 11:29:47 +08:00
sizes := regexp.MustCompile("^\\d+")
sizeRes := sizes.FindAllString(size, 1)
unit := strings.Split(size, sizeRes[0])
Res, _ := strconv.ParseInt(sizeRes[0], 10, 64)
2021-10-04 20:33:38 +08:00
sizeType := strings.ToUpper(unit[1])
switch {
case sizeType == "BIT" || sizeType == "B":
2021-10-25 11:08:18 +08:00
return Res, nil
2021-10-04 20:33:38 +08:00
case sizeType == "KB":
2021-10-25 11:08:18 +08:00
return Res * 1024, nil
case sizeType == "MB":
return Res * 1024 * 1024, nil
2021-10-04 20:33:38 +08:00
case sizeType == "GB":
2021-10-25 11:08:18 +08:00
return Res * 1024 * 1024 * 1024, nil
2021-10-04 20:33:38 +08:00
default:
return 0, errorx.New("your size is wrong")
2021-09-27 11:29:47 +08:00
}
}