Workiva / go-datastructures

A collection of useful, performant, and threadsafe Go datastructures.
Apache License 2.0
7.63k stars 833 forks source link

Add `GetSetBits` and `Count` to `BitArray` #221

Closed danielway-wk closed 1 year ago

danielway-wk commented 1 year ago

This adds two new functions to the BitArray interface for efficient access to set bits.

GetSetBits returns the position of bits set in the array. It is provided a position to start from and will fill the buffer with as many set bits as fit. Its implementation is based on TrailingZeros64 from math/bits.

Example usage:

ba := newBitArray(10)
ba.SetBit(1)
ba.SetBit(4)
ba.SetBit(8)

buffer := make([]uint64, 0, 2)
assert.Equal(t, []uint64{1, 4}, ba.GetSetBits(0, buffer))
assert.Equal(t, []uint64{8}, ba.GetSetBits(5, buffer))

Count returns the total number of bits set in the array. Its implementation is based on OnesCount64 from math/bits.

Example usage:

ba := newBitArray(10)
ba.SetBit(1)
ba.SetBit(4)
ba.SetBit(8)

assert.Equal(t, 3, ba.Count())

ba.ClearBit(4)
assert.Equal(t, 2, ba.Count())

ba.Reset()
assert.Equal(t, 0, ba.Count())
aviary3-wk commented 1 year ago

Security Insights

No security relevant content was detected by automated scans.

Action Items

dustinhiatt-wf commented 1 year ago

@Workiva/release-management-p