Skip to content

Commit

Permalink
Add ParseBytesInt function (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
mstmdev authored Jan 19, 2024
1 parent aabd286 commit 6649552
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
9 changes: 9 additions & 0 deletions unit/unit.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,15 @@ func ParseBytes(s string) (bytes uint64, iec bool, err error) {
return bytes, iec, nil
}

// ParseBytesInt parse the string to bytes
func ParseBytesInt(s string) (int, error) {
bytes, err := humanize.ParseBytes(s)
if err != nil {
return 0, err
}
return int(bytes), nil
}

// Bytes produces a human readable representation of an SI size
func Bytes(b uint64) string {
return humanize.Bytes(b)
Expand Down
19 changes: 17 additions & 2 deletions unit/unit_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func TestParseBytes(t *testing.T) {
t.Run(tc.s, func(t *testing.T) {
bytes, iec, err := ParseBytes(tc.s)
if err != nil {
t.Errorf("parse bytes error => %v", err)
t.Errorf("ParseBytes error => %v", err)
return
}
if bytes != tc.v {
Expand All @@ -68,6 +68,16 @@ func TestParseBytes(t *testing.T) {
t.Errorf("IEC expect %v, but get %v", tc.iec, iec)
return
}

bytesInt, err := ParseBytesInt(tc.s)
if err != nil {
t.Errorf("ParseBytesInt error => %v", err)
return
}
if bytesInt != int(tc.v) {
t.Errorf("expect %d, but get %d", tc.v, bytesInt)
return
}
})
}
}
Expand All @@ -84,7 +94,12 @@ func TestParseBytesReturnError(t *testing.T) {
t.Run(tc.s, func(t *testing.T) {
_, _, err := ParseBytes(tc.s)
if err == nil {
t.Errorf("expect get an error, but get nil")
t.Errorf("ParseBytes expect get an error, but get nil")
}

_, err = ParseBytesInt(tc.s)
if err == nil {
t.Errorf("ParseBytesInt expect get an error, but get nil")
}
})
}
Expand Down

0 comments on commit 6649552

Please sign in to comment.