2024-11-18 07:21:08 -05:00
|
|
|
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,
|
|
|
|
}
|
|
|
|
|
2024-11-21 12:30:26 -05:00
|
|
|
unitsSlice := []string{
|
|
|
|
"TB",
|
|
|
|
"GB",
|
|
|
|
"MB",
|
|
|
|
"KB",
|
|
|
|
"B",
|
|
|
|
}
|
|
|
|
|
2024-11-18 07:21:08 -05:00
|
|
|
var unit string
|
|
|
|
var value float64
|
|
|
|
|
2024-11-21 12:30:26 -05:00
|
|
|
for _, u := range unitsSlice {
|
2024-11-18 07:21:08 -05:00
|
|
|
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
|
2024-11-22 10:50:36 -05:00
|
|
|
GB
|
2024-11-18 07:21:08 -05:00
|
|
|
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:
|
2024-11-21 13:10:03 -05:00
|
|
|
return fmt.Sprintf("%d B", size)
|
2024-11-18 07:21:08 -05:00
|
|
|
}
|
|
|
|
}
|