Skip to content

Commit

Permalink
Clear unused bits in Not() (#38)
Browse files Browse the repository at this point in the history
  • Loading branch information
farazdagi committed Jan 21, 2021
1 parent c321497 commit fee7b72
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 1 deletion.
9 changes: 9 additions & 0 deletions bitlist64.go
Expand Up @@ -308,6 +308,7 @@ func (b *Bitlist64) NoAllocNot(ret *Bitlist64) {
for idx, word := range b.data {
ret.data[idx] = ^word
}
ret.clearUnusedBits()
}

// BitIndices returns list of bit indexes of bitlist where value is set to true.
Expand Down Expand Up @@ -367,3 +368,11 @@ func (b *Bitlist64) Clone() *Bitlist64 {
func numWordsRequired(n uint64) int {
return int((n + (wordSize - 1)) >> wordSizeLog2)
}

// clearUnusedBits zeroes unused bits in the last word.
func (b *Bitlist64) clearUnusedBits() {
// Unless bitlist is divisible by a word evenly, we need to zero unused bits in the last word.
if !(b.size%wordSize == 0) {
b.data[len(b.data)-1] &= allBitsSet >> (wordSize - b.size%wordSize)
}
}
12 changes: 11 additions & 1 deletion bitlist64_test.go
Expand Up @@ -1195,6 +1195,16 @@ func TestBitlist64_Not(t *testing.T) {
a: NewBitlist64From([]uint64{}), // zero-length bitlist
want: NewBitlist64From([]uint64{}),
},
{
// Last word bits are unused, single word.
a: NewBitlist64(3), // 0b*****000
want: NewBitlist64From([]uint64{0x07}), // 0b00000111
},
{
// Last word bits are unused, multiple words.
a: NewBitlist64(131), // 0x00..00, 0x00..00, 0b*****000
want: NewBitlist64From([]uint64{allBitsSet, allBitsSet, 0x07}), // 0xFF..FF, 0xFF..FF, 0b00000111
},
{
a: NewBitlist64From([]uint64{0x01}), // 0b00000001
want: NewBitlist64From([]uint64{0xFFFFFFFFFFFFFFFE}), // 0b11111110
Expand Down Expand Up @@ -1252,7 +1262,7 @@ func TestBitlist64_Not(t *testing.T) {
t.Run("Not()", func(t *testing.T) {
for _, tt := range tests {
if !reflect.DeepEqual(tt.a.Not().data, tt.want.data) {
t.Errorf("(%+v).Not() = %x, wanted %x", tt.a, tt.a.Not().data, tt.want)
t.Errorf("(%+v).Not() = %x, wanted %x", tt.a, tt.a.Not().data, tt.want.data)
}
}
})
Expand Down

0 comments on commit fee7b72

Please sign in to comment.