pcgamedb/utils/size.go
nite07 543210a4ae
All checks were successful
docker / prepare-and-build (push) Successful in 2m49s
release / goreleaser (push) Successful in 24m5s
reorganized game infos
change ranking route to popular route
2024-11-22 23:50:36 +08:00

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)
}
}