diff --git a/crypto/types/compact_bit_array.go b/crypto/types/compact_bit_array.go index 02d02e811b..1bbd5ec07d 100644 --- a/crypto/types/compact_bit_array.go +++ b/crypto/types/compact_bit_array.go @@ -6,6 +6,7 @@ import ( "errors" "fmt" "math" + "math/bits" "regexp" "strings" ) @@ -85,23 +86,18 @@ func (bA *CompactBitArray) SetIndex(i int, v bool) bool { // given index. e.g. if bA = _XX__XX, NumOfTrueBitsBefore(4) = 2, since // there are two bits set to true before index 4. func (bA *CompactBitArray) NumTrueBitsBefore(index int) int { - numTrueValues := 0 + onesCount := 0 max := bA.Count() if index > max { index = max } // below we iterate over the bytes then over bits (in low endian) and count bits set to 1 - var i = 0 for elem := 0; ; elem++ { - for b := 7; b >= 0; b-- { - if i >= index { - return numTrueValues - } - i++ - if (bA.Elems[elem]>>b)&1 == 1 { - numTrueValues++ - } + if elem*8+7 >= index { + onesCount += bits.OnesCount8(bA.Elems[elem] >> (7 - (index % 8) + 1)) + return onesCount } + onesCount += bits.OnesCount8(bA.Elems[elem]) } }