71 lines
1.2 KiB
Go
71 lines
1.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"fmt"
|
|
"strconv"
|
|
"strings"
|
|
)
|
|
|
|
func SizeToBytes(size string) (uint64, error) {
|
|
size = strings.TrimSpace(strings.ToUpper(size))
|
|
|
|
units := map[string]uint64{
|
|
"B": 1,
|
|
"KB": 1024,
|
|
"MB": 1024 * 1024,
|
|
"GB": 1024 * 1024 * 1024,
|
|
"TB": 1024 * 1024 * 1024 * 1024,
|
|
}
|
|
|
|
unitsSlice := []string{
|
|
"TB",
|
|
"GB",
|
|
"MB",
|
|
"KB",
|
|
"B",
|
|
}
|
|
|
|
var unit string
|
|
var value float64
|
|
|
|
for _, u := range unitsSlice {
|
|
if strings.HasSuffix(size, u) {
|
|
unit = u
|
|
numStr := strings.TrimSuffix(size, u)
|
|
val, err := strconv.ParseFloat(strings.TrimSpace(numStr), 64)
|
|
if err != nil {
|
|
return 0, err
|
|
}
|
|
value = val
|
|
break
|
|
}
|
|
}
|
|
|
|
if unit == "" {
|
|
return 0, fmt.Errorf("invalid unit in size: %s", size)
|
|
}
|
|
|
|
bytes := uint64(value * float64(units[unit]))
|
|
return bytes, nil
|
|
}
|
|
|
|
func BytesToSize(size uint64) string {
|
|
const (
|
|
_ = iota
|
|
KB uint64 = 1 << (10 * iota)
|
|
MB
|
|
GB
|
|
TB
|
|
)
|
|
switch {
|
|
case size >= GB:
|
|
return fmt.Sprintf("%.1f GB", float64(size)/float64(GB))
|
|
case size >= MB:
|
|
return fmt.Sprintf("%.1f MB", float64(size)/float64(MB))
|
|
case size >= KB:
|
|
return fmt.Sprintf("%.1f KB", float64(size)/float64(KB))
|
|
default:
|
|
return fmt.Sprintf("%d B", size)
|
|
}
|
|
}
|