matterbridge/vendor/github.com/labstack/gommon/bytes/bytes.go

110 lines
2.0 KiB
Go
Raw Normal View History

2017-02-18 22:00:46 +00:00
package bytes
import (
"fmt"
"regexp"
"strconv"
2019-09-07 20:46:58 +00:00
"strings"
2017-02-18 22:00:46 +00:00
)
type (
// Bytes struct
Bytes struct{}
2017-02-18 22:00:46 +00:00
)
const (
_ = 1.0 << (10 * iota) // ignore first value by assigning to blank identifier
2017-02-18 22:00:46 +00:00
KB
MB
GB
TB
PB
EB
)
var (
2019-06-16 21:33:25 +00:00
pattern = regexp.MustCompile(`(?i)^(-?\d+(?:\.\d+)?)\s?([KMGTPE]B?|B?)$`)
2017-02-18 22:00:46 +00:00
global = New()
)
// New creates a Bytes instance.
func New() *Bytes {
return &Bytes{}
}
// Format formats bytes integer to human readable string.
// For example, 31323 bytes will return 30.59KB.
func (*Bytes) Format(b int64) string {
multiple := ""
value := float64(b)
switch {
case b >= EB:
value /= EB
multiple = "EB"
case b >= PB:
2017-02-18 22:00:46 +00:00
value /= PB
multiple = "PB"
case b >= TB:
value /= TB
multiple = "TB"
case b >= GB:
value /= GB
multiple = "GB"
case b >= MB:
value /= MB
multiple = "MB"
case b >= KB:
value /= KB
multiple = "KB"
case b == 0:
return "0"
default:
return strconv.FormatInt(b, 10) + "B"
2017-02-18 22:00:46 +00:00
}
return fmt.Sprintf("%.2f%s", value, multiple)
2017-02-18 22:00:46 +00:00
}
// Parse parses human readable bytes string to bytes integer.
// For example, 6GB (6G is also valid) will return 6442450944.
func (*Bytes) Parse(value string) (i int64, err error) {
parts := pattern.FindStringSubmatch(value)
if len(parts) < 3 {
return 0, fmt.Errorf("error parsing value=%s", value)
}
bytesString := parts[1]
2019-09-07 20:46:58 +00:00
multiple := strings.ToUpper(parts[2])
bytes, err := strconv.ParseFloat(bytesString, 64)
2017-02-18 22:00:46 +00:00
if err != nil {
return
}
switch multiple {
default:
return int64(bytes), nil
2017-02-18 22:00:46 +00:00
case "K", "KB":
return int64(bytes * KB), nil
2017-02-18 22:00:46 +00:00
case "M", "MB":
return int64(bytes * MB), nil
2017-02-18 22:00:46 +00:00
case "G", "GB":
return int64(bytes * GB), nil
2017-02-18 22:00:46 +00:00
case "T", "TB":
return int64(bytes * TB), nil
2017-02-18 22:00:46 +00:00
case "P", "PB":
return int64(bytes * PB), nil
case "E", "EB":
return int64(bytes * EB), nil
2017-02-18 22:00:46 +00:00
}
}
// Format wraps global Bytes's Format function.
func Format(b int64) string {
return global.Format(b)
}
// Parse wraps global Bytes's Parse function.
func Parse(val string) (int64, error) {
return global.Parse(val)
}