Skip to content

Commit

Permalink
Define BitArray.Count and add test coverage
Browse files Browse the repository at this point in the history
  • Loading branch information
danielway-wk committed May 16, 2023
1 parent 9eab2df commit d95ee5d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 0 deletions.
22 changes: 22 additions & 0 deletions bitarray/bitarray_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,28 @@ func TestIsEmpty(t *testing.T) {
assert.False(t, ba.IsEmpty())
}

func TestCount(t *testing.T) {
ba := newBitArray(500)
assert.Equal(t, uint64(0), ba.Count())

require.NoError(t, ba.SetBit(0))
assert.Equal(t, uint64(1), ba.Count())

require.NoError(t, ba.SetBit(40))
require.NoError(t, ba.SetBit(64))
require.NoError(t, ba.SetBit(100))
require.NoError(t, ba.SetBit(200))
require.NoError(t, ba.SetBit(469))
require.NoError(t, ba.SetBit(500))
assert.Equal(t, uint64(7), ba.Count())

require.NoError(t, ba.ClearBit(200))
assert.Equal(t, uint64(6), ba.Count())

ba.Reset()
assert.Equal(t, uint64(0), ba.Count())
}

func TestClear(t *testing.T) {
ba := newBitArray(10)

Expand Down
2 changes: 2 additions & 0 deletions bitarray/interface.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,8 @@ type BitArray interface {
// in the case of a dense bit array or the highest possible
// seen capacity of the sparse array.
Capacity() uint64
// Count returns the number of set bits in this array.
Count() uint64
// Or will bitwise or the two bitarrays and return a new bitarray
// representing the result.
Or(other BitArray) BitArray
Expand Down
22 changes: 22 additions & 0 deletions bitarray/sparse_bitarray_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,6 +119,28 @@ func BenchmarkGetSetCompressedBits(b *testing.B) {
}
}

func TestCompressedCount(t *testing.T) {
ba := newSparseBitArray()
assert.Equal(t, uint64(0), ba.Count())

require.NoError(t, ba.SetBit(0))
assert.Equal(t, uint64(1), ba.Count())

require.NoError(t, ba.SetBit(40))
require.NoError(t, ba.SetBit(64))
require.NoError(t, ba.SetBit(100))
require.NoError(t, ba.SetBit(200))
require.NoError(t, ba.SetBit(469))
require.NoError(t, ba.SetBit(500))
assert.Equal(t, uint64(7), ba.Count())

require.NoError(t, ba.ClearBit(200))
assert.Equal(t, uint64(6), ba.Count())

ba.Reset()
assert.Equal(t, uint64(0), ba.Count())
}

func TestClearCompressedBit(t *testing.T) {
ba := newSparseBitArray()
ba.SetBit(5)
Expand Down

0 comments on commit d95ee5d

Please sign in to comment.