qcc/internal/server/bandwidth.go
2026-06-30 12:52:09 +03:00

46 lines
831 B
Go

package server
import (
"errors"
"strconv"
"strings"
)
const (
_byte = 1
kilobyte = _byte * 1000
megabyte = kilobyte * 1000
gigabyte = megabyte * 1000
)
func parseBandwidth(s string) (uint64, error) {
s = strings.ToLower(strings.TrimSpace(s))
split := 0
for i, c := range s {
if c < '0' || c > '9' {
split = i
break
}
}
if split == 0 {
return 0, errors.New("invalid bandwidth format")
}
v, err := strconv.ParseUint(s[:split], 10, 64)
if err != nil {
return 0, err
}
unit := strings.TrimSpace(s[split:])
switch unit {
case "b", "bps":
return v / 8, nil
case "k", "kb", "kbps":
return v * kilobyte / 8, nil
case "m", "mb", "mbps":
return v * megabyte / 8, nil
case "g", "gb", "gbps":
return v * gigabyte / 8, nil
default:
return 0, errors.New("unsupported bandwidth unit")
}
}