Skip to content

Commit

Permalink
fix(bits): handle last element in PickRandom (backport cometbft#2899) (
Browse files Browse the repository at this point in the history
…cometbft#2902) (#35)

Follow-up to cometbft#2841

---

#### PR checklist

- [x] Tests written/updated
- [ ] ~~Changelog entry added in `.changelog` (we use
[unclog](https://github.com/informalsystems/unclog) to manage our
changelog)~~
- [ ] ~~Updated relevant documentation (`docs/` or `spec/`) and code
comments~~
- [x] Title follows the [Conventional
Commits](https://www.conventionalcommits.org/en/v1.0.0/) spec
<hr>This is an automatic backport of pull request cometbft#2899 done by
[Mergify](https://mergify.com).

Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>
Co-authored-by: Anton Kaliaev <[email protected]>
  • Loading branch information
3 people authored May 2, 2024
1 parent a1f675e commit 08efc4c
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 1 deletion.
10 changes: 9 additions & 1 deletion libs/bits/bit_array.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,9 +264,17 @@ func (bA *BitArray) PickRandom() (int, bool) {
func (bA *BitArray) getNumTrueIndices() int {
count := 0
numElems := len(bA.Elems)
for i := 0; i < numElems; i++ {
// handle all elements except the last one
for i := 0; i < numElems-1; i++ {
count += bits.OnesCount64(bA.Elems[i])
}
// handle last element
numFinalBits := bA.Bits - (numElems-1)*64
for i := 0; i < numFinalBits; i++ {
if (bA.Elems[numElems-1] & (uint64(1) << uint64(i))) > 0 {
count++
}
}
return count
}

Expand Down
2 changes: 2 additions & 0 deletions libs/bits/bit_array_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -173,6 +173,8 @@ func TestGetNumTrueIndices(t *testing.T) {
require.NoError(t, err)
result := bitArr.getNumTrueIndices()
require.Equal(t, tc.ExpectedResult, result, "for input %s, expected %d, got %d", tc.Input, tc.ExpectedResult, result)
result = bitArr.Not().getNumTrueIndices()
require.Equal(t, bitArr.Bits-result, bitArr.getNumTrueIndices())
}
}

Expand Down

0 comments on commit 08efc4c

Please sign in to comment.