Skip to content

Commit

Permalink
Fix CountTo (#37)
Browse files Browse the repository at this point in the history
* Fix CountTo

* don't panic when passing index past slice bounds
  • Loading branch information
mhr3 authored Nov 6, 2023
1 parent c15d0a3 commit 649a9ff
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
15 changes: 9 additions & 6 deletions bitmap.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,18 +123,21 @@ func (dst Bitmap) CountTo(until uint32) int {
return 0
}

// Figure out the index of the last block
blkUntil := int(until >> 6)
bitUntil := int(until % 64)
if blkUntil >= len(dst) {
blkUntil = len(dst) - 1
if maxUntil := uint32(len(dst) << 6); until > maxUntil {
until = maxUntil
}

// Figure out the index of the last block
blkUntil := until >> 6
bitUntil := until % 64

// Count the bits right before the last block
sum := dst[:blkUntil].Count()

// Count the bits at the end
sum += bits.OnesCount64(dst[blkUntil] << (64 - uint64(bitUntil)))
if bitUntil > 0 {
sum += bits.OnesCount64(dst[blkUntil] << (64 - uint64(bitUntil)))
}
return sum
}

Expand Down
5 changes: 5 additions & 0 deletions bitmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -392,7 +392,12 @@ func TestCount(t *testing.T) {
assert.Equal(t, 4, b.CountTo(100))
assert.Equal(t, 4, b.CountTo(101))
assert.Equal(t, 5, b.CountTo(102))
assert.Equal(t, 8, b.CountTo(128))
assert.Equal(t, 8, b.CountTo(math.MaxUint32))

b.Set(127)

assert.Equal(t, 9, b.CountTo(128))
}

func TestGrow(t *testing.T) {
Expand Down

0 comments on commit 649a9ff

Please sign in to comment.