diff --git a/bitset.go b/bitset.go index 4c271e1..334367d 100644 --- a/bitset.go +++ b/bitset.go @@ -602,6 +602,56 @@ func (b *BitSet) NextClear(i uint) (uint, bool) { return 0, false } +// PreviousSet returns the previous set bit from the specified index, +// including possibly the current index +// along with an error code (true = valid, false = no bit found i.e. all bits are clear) +func (b *BitSet) PreviousSet(i uint) (uint, bool) { + x := int(i >> log2WordSize) + if x >= len(b.set) { + return 0, false + } + w := b.set[x] + // Clear the bits above the index + w = w & ((1 << (wordsIndex(i) + 1)) - 1) + if w != 0 { + return uint(x<= 0; x-- { + w = b.set[x] + if w != 0 { + return uint(x<> log2WordSize) + if x >= len(b.set) { + return 0, false + } + w := b.set[x] + // Flip all bits and find the highest one bit + w = ^w + // Clear the bits above the index + w = w & ((1 << (wordsIndex(i) + 1)) - 1) + if w != 0 { + return uint(x<= 0; x-- { + w = b.set[x] + w = ^w + if w != 0 { + return uint(x<