Skip to content

Commit

Permalink
cli: info does not segfault on large byte values (#1062)
Browse files Browse the repository at this point in the history
### Public-Facing Changes

* CLI: fixes a segfault when an MCAP contains >1024 GiB of data OR
results in an greater "data rate" than 1024GiB/s

### Description

Previously the `humanBytes` function would segfault when presented with
a number > 1024^4.
  • Loading branch information
james-rms authored Feb 14, 2024
1 parent 2eb67b0 commit ac69dc6
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 5 deletions.
14 changes: 9 additions & 5 deletions go/cli/mcap/cmd/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,16 @@ func decimalTime(t time.Time) string {

func humanBytes(numBytes uint64) string {
prefixes := []string{"B", "KiB", "MiB", "GiB"}
displayedValue := float64(numBytes)
prefixIndex := 0
for ; displayedValue > 1024 && prefixIndex < len(prefixes); prefixIndex++ {
displayedValue /= 1024

for index, p := range prefixes {
displayedValue := float64(numBytes) / (math.Pow(1024, float64(index)))
if displayedValue <= 1024 {
return fmt.Sprintf("%.2f %s", displayedValue, p)
}
}
return fmt.Sprintf("%.2f %s", displayedValue, prefixes[prefixIndex])
lastIndex := len(prefixes) - 1
displayedValue := float64(numBytes) / (math.Pow(1024, float64(lastIndex)))
return fmt.Sprintf("%.2f %s", displayedValue, prefixes[lastIndex])
}

func getDurationNs(start uint64, end uint64) float64 {
Expand Down
18 changes: 18 additions & 0 deletions go/cli/mcap/cmd/info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -39,3 +39,21 @@ func TestInfo(t *testing.T) {
})
assert.Nil(t, err)
}

func TestHumanBytes(t *testing.T) {
cases := []struct {
n uint64
result string
}{
{2, "2.00 B"},
{1024 * 2, "2.00 KiB"},
{1024 * 1024 * 2, "2.00 MiB"},
{1024 * 1024 * 1024 * 2, "2.00 GiB"},
{1024 * 1024 * 1024 * 1024 * 2, "2048.00 GiB"},
}
for _, c := range cases {
t.Run(c.result, func(t *testing.T) {
assert.Equal(t, c.result, humanBytes(c.n))
})
}
}

0 comments on commit ac69dc6

Please sign in to comment.