chore: move code around

This commit is contained in:
Toby 2023-08-23 16:26:38 -07:00
parent 3c3c2a51a8
commit 332d2ea32d
8 changed files with 137 additions and 126 deletions

View file

@ -1,52 +0,0 @@
package utils
import (
"errors"
"strconv"
"strings"
)
const (
Byte = 1.0 << (10 * iota)
Kilobyte
Megabyte
Gigabyte
Terabyte
)
// StringToBps converts a string to a bandwidth value in bytes per second.
// E.g. "100 Mbps", "512 kbps", "1g" are all valid.
func StringToBps(s string) (uint64, error) {
s = strings.ToLower(strings.TrimSpace(s))
spl := 0
for i, c := range s {
if c < '0' || c > '9' {
spl = i
break
}
}
if spl == 0 {
// No unit or no value
return 0, errors.New("invalid format")
}
v, err := strconv.ParseUint(s[:spl], 10, 64)
if err != nil {
return 0, err
}
unit := strings.TrimSpace(s[spl:])
switch strings.ToLower(unit) {
case "b", "bps":
return v * Byte / 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
case "t", "tb", "tbps":
return v * Terabyte / 8, nil
default:
return 0, errors.New("unsupported unit")
}
}

View file

@ -1,40 +0,0 @@
package utils
import "testing"
func TestStringToBps(t *testing.T) {
type args struct {
s string
}
tests := []struct {
name string
args args
want uint64
wantErr bool
}{
{"bps", args{"800 bps"}, 100, false},
{"kbps", args{"800 kbps"}, 102400, false},
{"mbps", args{"800 mbps"}, 104857600, false},
{"gbps", args{"800 gbps"}, 107374182400, false},
{"tbps", args{"800 tbps"}, 109951162777600, false},
{"mbps simp", args{"100m"}, 13107200, false},
{"gbps simp upper", args{"2G"}, 268435456, false},
{"invalid 1", args{"damn"}, 0, true},
{"invalid 2", args{"6444"}, 0, true},
{"invalid 3", args{"5.4 mbps"}, 0, true},
{"invalid 4", args{"kbps"}, 0, true},
{"invalid 5", args{"1234 5678 gbps"}, 0, true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := StringToBps(tt.args.s)
if (err != nil) != tt.wantErr {
t.Errorf("StringToBps() error = %v, wantErr %v", err, tt.wantErr)
return
}
if got != tt.want {
t.Errorf("StringToBps() got = %v, want %v", got, tt.want)
}
})
}
}