/
bitset.go
353 lines (325 loc) · 7.43 KB
/
bitset.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
package bitset
import (
"bytes"
"encoding/hex"
"errors"
"fmt"
"math/bits"
"sync"
"github.com/andeya/goutil"
)
// BitSet bit set
type BitSet struct {
set []byte
mu sync.RWMutex
}
// New creates a bit set object.
func New(init ...byte) *BitSet {
return &BitSet{set: init}
}
// NewFromHex creates a bit set object from hex string.
func NewFromHex(s string) (*BitSet, error) {
init, err := hex.DecodeString(s)
if err != nil {
return nil, err
}
return &BitSet{set: init}, nil
}
// Set sets the bit bool value on the specified offset,
// and returns the value of before setting.
// NOTE:
// 0 means the 1st bit, -1 means the bottom 1th bit, -2 means the bottom 2th bit and so on;
// If offset>=len(b.set), automatically grow the bit set;
// If the bit offset is out of the left range, returns error.
func (b *BitSet) Set(offset int, value bool) (bool, error) {
b.mu.Lock()
defer b.mu.Unlock()
size := b.size()
// 0 means the 1st bit, -1 means the bottom 1th bit,
// -2 means the bottom 2th bit and so on.
if offset < 0 {
offset += size
}
if offset < 0 {
return false, errors.New("the bit offset is out of the left range")
}
// the bit group index
gi := offset / 8
// the bit index of in the group
bi := offset % 8
// if the bit offset is out of the right range, automatically grow.
if gi >= len(b.set) {
newSet := make([]byte, gi+1)
copy(newSet, b.set)
b.set = newSet
}
gb := b.set[gi]
rOff := byte(7 - bi)
var mask byte = 1 << rOff
oldVal := gb & mask >> rOff
if (oldVal == 1) != value {
if oldVal == 1 {
b.set[gi] = gb &^ mask
} else {
b.set[gi] = gb | mask
}
}
return oldVal == 1, nil
}
// Get gets the bit bool value on the specified offset.
// NOTE:
// 0 means the 1st bit, -1 means the bottom 1th bit, -2 means the bottom 2th bit and so on;
// If offset>=len(b.set), returns false.
func (b *BitSet) Get(offset int) bool {
b.mu.RLock()
defer b.mu.RUnlock()
size := b.size()
// 0 means the 1st bit, -1 means the bottom 1th bit,
// -2 means the bottom 2th bit and so on.
if offset < 0 {
offset += size
}
if offset < 0 || offset >= size {
return false
}
return getBit(b.set[offset/8], byte(offset%8)) == 1
}
// Range calls f sequentially for each bit present in the bit set.
// If f returns false, range stops the iteration.
func (b *BitSet) Range(f func(offset int, truth bool) bool) {
b.mu.RLock()
defer b.mu.RUnlock()
size := b.size()
if size == 0 {
return
}
for offset := 0; offset < size; offset++ {
if !f(offset, getBit(b.set[offset/8], byte(offset%8)) == 1) {
return
}
}
}
func getBit(gb, offset byte) byte {
var rOff = 7 - offset
var mask byte = 1 << rOff
return gb & mask >> rOff
}
// Count counts the amount of bit set to 1 within the specified range of the bit set.
// NOTE:
// 0 means the 1st bit, -1 means the bottom 1th bit, -2 means the bottom 2th bit and so on.
func (b *BitSet) Count(start, end int) int {
b.mu.RLock()
defer b.mu.RUnlock()
sgi, sbi, egi, ebi, valid := b.validRange(start, end)
if !valid {
return 0
}
var n int
n += bits.OnesCount8(b.set[sgi] << sbi)
for _, v := range b.set[sgi+1 : egi] {
n += bits.OnesCount8(v)
}
n += bits.OnesCount8(b.set[egi] >> (7 - ebi) << (7 - ebi))
return n
}
func (b *BitSet) validRange(start, end int) (sgi, sbi, egi, ebi uint, valid bool) {
size := b.size()
if start < 0 {
start += size
}
if start >= size {
return
}
if start < 0 {
start = 0
}
if end < 0 {
end += size
}
if end >= size {
end = size - 1
}
if start > end {
return
}
valid = true
sgi, sbi = uint(start/8), uint(start%8)
egi, ebi = uint(end/8), uint(end%8)
return
}
// Not returns ^b.
func (b *BitSet) Not() *BitSet {
b.mu.RLock()
defer b.mu.RUnlock()
rBitSet := &BitSet{
set: make([]byte, len(b.set)),
}
for i, gb := range b.set {
rBitSet.set[i] = ^gb
}
return rBitSet
}
// And returns all the "AND" bit sets.
// NOTE:
// If the bitSets are empty, returns b.
func (b *BitSet) And(bitSets ...*BitSet) *BitSet {
b.mu.RLock()
defer b.mu.RUnlock()
if len(bitSets) == 0 {
return b
}
var (
maxLen = len(b.set)
minLen = maxLen
currLen int
)
for _, g := range bitSets {
g.mu.RLock()
defer g.mu.RUnlock()
currLen = len(g.set)
if currLen > maxLen {
maxLen = currLen
} else if currLen < minLen {
minLen = currLen
}
}
rBitSet := &BitSet{
set: make([]byte, maxLen),
}
for i := range rBitSet.set[:minLen] {
rBitSet.set[i] = b.set[i]
for _, g := range bitSets {
rBitSet.set[i] &= g.set[i]
}
}
return rBitSet
}
// Or returns all the "OR" bit sets.
// NOTE:
// If the bitSets are empty, returns b.
func (b *BitSet) Or(bitSet ...*BitSet) *BitSet {
return b.op("|", bitSet)
}
// Xor returns all the "XOR" bit sets.
// NOTE:
// If the bitSets are empty, returns b.
func (b *BitSet) Xor(bitSet ...*BitSet) *BitSet {
return b.op("^", bitSet)
}
// AndNot returns all the "&^" bit sets.
// NOTE:
// If the bitSets are empty, returns b.
func (b *BitSet) AndNot(bitSet ...*BitSet) *BitSet {
return b.op("&^", bitSet)
}
func (b *BitSet) op(op string, bitSets []*BitSet) *BitSet {
if len(bitSets) == 0 {
return b
}
b.mu.RLock()
defer b.mu.RUnlock()
var (
maxLen, currLen = len(b.set), 0
)
for _, g := range bitSets {
g.mu.RLock()
defer g.mu.RUnlock()
currLen = len(g.set)
if currLen > maxLen {
maxLen = currLen
}
}
rBitSet := &BitSet{
set: make([]byte, maxLen),
}
copy(rBitSet.set, b.set)
for _, g := range bitSets {
for i, gb := range g.set {
switch op {
case "|":
rBitSet.set[i] = rBitSet.set[i] | gb
case "^":
rBitSet.set[i] = rBitSet.set[i] ^ gb
case "&^":
rBitSet.set[i] = rBitSet.set[i] &^ gb
}
}
}
return rBitSet
}
// Clear clears the bit set.
func (b *BitSet) Clear() {
b.mu.Lock()
for i := range b.set {
b.set[i] = 0
}
b.mu.Unlock()
}
// Size returns the bits size.
func (b *BitSet) Size() int {
b.mu.RLock()
size := b.size()
b.mu.RUnlock()
return size
}
func (b *BitSet) size() int {
size := len(b.set) * 8
if size/8 != len(b.set) {
panic("overflow when calculating the bit set size")
}
return size
}
// Bytes returns the bit set copy bytes.
func (b *BitSet) Bytes() []byte {
b.mu.RLock()
set := make([]byte, len(b.set))
copy(set, b.set)
b.mu.RUnlock()
return set
}
// Binary returns the bit set by binary type.
// NOTE:
// Paramter sep is the separator between chars.
func (b *BitSet) Binary(sep string) string {
b.mu.RLock()
defer b.mu.RUnlock()
if len(b.set) == 0 {
return ""
}
var buf bytes.Buffer
for _, i := range b.set {
buf.WriteString(fmt.Sprintf("%s%08b", sep, i))
}
return goutil.BytesToString(bytes.TrimPrefix(buf.Bytes(), goutil.StringToBytes(sep)))
}
// String returns the bit set by hex type.
func (b *BitSet) String() string {
b.mu.RLock()
defer b.mu.RUnlock()
return hex.EncodeToString(b.set)
}
// Sub returns the bit subset within the specified range of the bit set.
// NOTE:
// 0 means the 1st bit, -1 means the bottom 1th bit, -2 means the bottom 2th bit and so on.
func (b *BitSet) Sub(start, end int) *BitSet {
b.mu.RLock()
defer b.mu.RUnlock()
newBitSet := &BitSet{
set: make([]byte, 0, len(b.set)),
}
sgi, sbi, egi, ebi, valid := b.validRange(start, end)
if !valid {
return newBitSet
}
pre := b.set[sgi] << sbi
for _, v := range b.set[sgi+1 : egi] {
newBitSet.set = append(newBitSet.set, pre|v>>(7-sbi))
pre = v << sbi
}
last := b.set[egi] >> (7 - ebi) << (7 - ebi)
newBitSet.set = append(newBitSet.set, pre|last>>(7-sbi))
if sbi < ebi {
newBitSet.set = append(newBitSet.set, last<<sbi)
}
return newBitSet
}