| 1 |
package sievecache |
| 2 |
|
| 3 |
import ( |
| 4 |
"math/bits" |
| 5 |
) |
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
type BitSet struct { |
| 10 |
bits []uint64 |
| 11 |
size int |
| 12 |
} |
| 13 |
|
| 14 |
|
| 15 |
func NewBitSet(capacity int) *BitSet { |
| 16 |
|
| 17 |
numWords := (capacity + 63) / 64 |
| 18 |
return &BitSet{ |
| 19 |
bits: make([]uint64, numWords), |
| 20 |
size: capacity, |
| 21 |
} |
| 22 |
} |
| 23 |
|
| 24 |
|
| 25 |
func (b *BitSet) Set(index int, value bool) { |
| 26 |
if index >= b.size { |
| 27 |
b.resize(index + 1) |
| 28 |
} |
| 29 |
|
| 30 |
wordIndex := index >> 6 |
| 31 |
bitIndex := index & 0x3F |
| 32 |
|
| 33 |
if value { |
| 34 |
b.bits[wordIndex] |= 1 << bitIndex |
| 35 |
} else { |
| 36 |
b.bits[wordIndex] &= ^(1 << bitIndex) |
| 37 |
} |
| 38 |
} |
| 39 |
|
| 40 |
|
| 41 |
func (b *BitSet) Get(index int) bool { |
| 42 |
if index >= b.size { |
| 43 |
return false |
| 44 |
} |
| 45 |
|
| 46 |
wordIndex := index >> 6 |
| 47 |
bitIndex := index & 0x3F |
| 48 |
|
| 49 |
return (b.bits[wordIndex] & (1 << bitIndex)) != 0 |
| 50 |
} |
| 51 |
|
| 52 |
|
| 53 |
func (b *BitSet) resize(newSize int) { |
| 54 |
if newSize <= b.size { |
| 55 |
return |
| 56 |
} |
| 57 |
|
| 58 |
|
| 59 |
numWords := (newSize + 63) >> 6 |
| 60 |
|
| 61 |
|
| 62 |
if numWords > len(b.bits) { |
| 63 |
|
| 64 |
newCap := len(b.bits) |
| 65 |
if newCap < 4 { |
| 66 |
newCap = 4 |
| 67 |
} |
| 68 |
for newCap < numWords { |
| 69 |
newCap += newCap >> 1 |
| 70 |
} |
| 71 |
|
| 72 |
newBits := make([]uint64, numWords, newCap) |
| 73 |
copy(newBits, b.bits) |
| 74 |
b.bits = newBits |
| 75 |
} |
| 76 |
|
| 77 |
b.size = newSize |
| 78 |
} |
| 79 |
|
| 80 |
|
| 81 |
func (b *BitSet) Append(value bool) { |
| 82 |
b.Set(b.size, value) |
| 83 |
} |
| 84 |
|
| 85 |
|
| 86 |
func (b *BitSet) Truncate(newSize int) { |
| 87 |
if newSize >= b.size { |
| 88 |
return |
| 89 |
} |
| 90 |
|
| 91 |
|
| 92 |
numWords := (newSize + 63) >> 6 |
| 93 |
|
| 94 |
|
| 95 |
if numWords > 0 { |
| 96 |
lastWordBits := newSize & 0x3F |
| 97 |
if lastWordBits > 0 { |
| 98 |
|
| 99 |
mask := (uint64(1) << lastWordBits) - 1 |
| 100 |
|
| 101 |
b.bits[numWords-1] &= mask |
| 102 |
} |
| 103 |
} |
| 104 |
|
| 105 |
|
| 106 |
if numWords < len(b.bits) { |
| 107 |
b.bits = b.bits[:numWords] |
| 108 |
} |
| 109 |
|
| 110 |
b.size = newSize |
| 111 |
} |
| 112 |
|
| 113 |
|
| 114 |
func (b *BitSet) Size() int { |
| 115 |
return b.size |
| 116 |
} |
| 117 |
|
| 118 |
|
| 119 |
func (b *BitSet) CountSetBits() int { |
| 120 |
var count int |
| 121 |
for _, word := range b.bits { |
| 122 |
count += bits.OnesCount64(word) |
| 123 |
} |
| 124 |
return count |
| 125 |
} |