Skip to content

Commit

Permalink
add Word method with tests
Browse files Browse the repository at this point in the history
  • Loading branch information
CannibalVox committed Nov 5, 2024
1 parent 5f9e437 commit 063e841
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
22 changes: 22 additions & 0 deletions bitset.go
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,28 @@ func (b *BitSet) Test(i uint) bool {
return b.set[i>>log2WordSize]&(1<<wordsIndex(i)) != 0
}

// Word retrieves bits i through i+63 as a single uint64 value
func (b *BitSet) Word(i uint) uint64 {
firstWordIndex := int(i >> log2WordSize)
subWordIndex := wordsIndex(i)

// The word that the index falls within, shifted so the index is at bit 0
var firstWord, secondWord uint64
if firstWordIndex < len(b.set) {
firstWord = b.set[firstWordIndex] >> subWordIndex
}

// The next word, masked to only include the necessary bits and shifted to cover the
// top of the word
if (firstWordIndex + 1) < len(b.set) {
mask := uint64((1 << subWordIndex) - 1)

secondWord = (b.set[firstWordIndex+1] & mask) << uint64(wordSize-subWordIndex)
}

return firstWord | secondWord
}

// Set bit i to 1, the capacity of the bitset is automatically
// increased accordingly.
// Warning: using a very large value for 'i'
Expand Down
52 changes: 52 additions & 0 deletions bitset_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2035,3 +2035,55 @@ func TestShiftRight(t *testing.T) {
test("full shift", 89)
test("remove all", 242)
}

func TestWord(t *testing.T) {
data := []uint64{0x0bfd85fc01af96dd, 0x3fe212a7eae11414, 0x7aa412221245dee1, 0x557092c1711306d5}
testCases := map[string]struct {
index uint
expected uint64
}{
"first word": {
index: 0,
expected: 0x0bfd85fc01af96dd,
},
"third word": {
index: 128,
expected: 0x7aa412221245dee1,
},
"off the edge": {
index: 256,
expected: 0,
},
"way off the edge": {
index: 6346235235,
expected: 0,
},
"split between two words": {
index: 96,
expected: 0x1245dee13fe212a7,
},
"partly off edge": {
index: 254,
expected: 1,
},
"skip one nibble": {
index: 4,
expected: 0x40bfd85fc01af96d,
},
"slightly offset results": {
index: 65,
expected: 0x9ff10953f5708a0a,
},
}

for name, testCase := range testCases {
t.Run(name, func(t *testing.T) {
bitSet := From(data)
output := bitSet.Word(testCase.index)

if output != testCase.expected {
t.Errorf("Word should have returned %d for input %d, but returned %d", testCase.expected, testCase.index, output)
}
})
}
}

0 comments on commit 063e841

Please sign in to comment.