1
0
Fork 0
mirror of https://github.com/eosswedenorg/thalos synced 2026-08-23 19:48:12 +02:00

Adding app/types/size.go

This commit is contained in:
Henrik Hautakoski 2023-05-02 18:08:53 +02:00
parent 1cd741c610
commit 12f78d23ce
4 changed files with 72 additions and 0 deletions

35
app/types/size.go Normal file
View file

@ -0,0 +1,35 @@
package types
import (
"github.com/docker/go-units"
"gopkg.in/yaml.v3"
)
// Size is an alias of int64 that can handle sizes represented
// in human readable strings like "200mb", "20 GB" etc
type Size int64 // Size in bytes.
// Parse a string into number of bytes stored in a int64
func (s *Size) Parse(value string) error {
// Empty strings are not an error, they represents zero bytes.
if len(value) < 1 {
*s = 0
return nil
}
v, err := units.FromHumanSize(value)
if err != nil {
return err
}
*s = Size(v)
return nil
}
func (s Size) String() string {
return units.HumanSize(float64(s))
}
func (s *Size) UnmarshalYAML(value *yaml.Node) error {
return s.Parse(value.Value)
}

34
app/types/size_test.go Normal file
View file

@ -0,0 +1,34 @@
package types
import "testing"
func TestSize_Parse(t *testing.T) {
tests := []struct {
name string
value string
expected int64
wantErr bool
}{
{"Empty", "", 0, false},
{"NoDigit", "abcdefg", 0, true},
{"Negative", "-10MB", 0, true},
{"Invalid prefix", "100WAX", 0, true},
{"Multiple spaces between prefix and value", "100 gb", 0, true},
{"100kb", "100kb", 100 * 1000, false},
{"10MB", "10 MB", 10 * 1000 * 1000, false},
{"2gb", "2gb", 2 * 1000 * 1000 * 1000, false},
{"4Tb", "4 Tb", 4 * 1000 * 1000 * 1000 * 1000, false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
s := Size(0)
if err := s.Parse(tt.value); (err != nil) != tt.wantErr {
t.Errorf("Size.Parse() error = %v, wantErr %v", err, tt.wantErr)
}
if int64(s) != tt.expected {
t.Errorf("Size = %v, expected %v", s, tt.expected)
}
})
}
}