Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix CountTo #37

Merged
merged 2 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading