/
bitfield.go
401 lines (361 loc) · 9.22 KB
/
bitfield.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
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
Package bitfield is for storing and manipulating bit-data.
There are two structs defined: BitField64 is in case you want to store
64 or less bits, while BitField is for storing arbitrary number of bits.
*/
package bitfield
// BitField is a flexible size version of BitField64.
//
// Most functions are chainable, positions outside the [0,len) range
// will get the modulo treatment, so Get(len) will return the 0th bit, Get(-1)
// will return the last bit: Get(len-1)
//
// Most methods do not modify the underlying bitfield but create a new and
// return that. You can change this behaviour by calling .Mut() method. In this
// case all methods explicitely marked as 'Mutable.' will be modified in-place.
// This reduces allocations (for cases where speed does matter).
type BitField struct {
data []BitField64
len int
mutable bool
}
// New creates a new BitField of length len
func New(len int) *BitField {
return NewBitField(len)
}
// NewBitField creates a new BitField of length len and returns it.
// Panics if len<0
func NewBitField(len int) *BitField {
if len < 0 {
panic("len cannot be negative")
}
return &BitField{
data: make([]BitField64, 1+len/64),
len: len,
mutable: false,
}
}
// Mut sets the mutable flag. This can reduce number of copying
// if execution time is important. Methods where description contains
// 'Mutable.' will modify content in-place.
func (bf *BitField) Mut() *BitField {
bf.mutable = true
return bf
}
// resize always creates a new bitfield regardless of Mut()
func (bf *BitField) resize(newLen int) *BitField {
ret := NewBitField(newLen)
if newLen == 0 {
return ret
}
copy(ret.data, bf.data)
if newLen < bf.len {
ret.clearEnd()
}
return ret
}
// Resize resizes the bitfield to newLen in size.
// Panics is newLen<0
// Returns a newly allocated one, leaves the original intact.
// If newLen < Len() bits are lost at the end.
// If newLen > Len() the newly added bits will be zeroed.
// Mutable.
func (bf *BitField) Resize(newLen int) *BitField {
ret := bf.resize(newLen)
copy(ret.data, bf.data)
if newLen < bf.len {
ret.clearEnd()
}
if bf.mutable {
bf.data = ret.data
bf.len = ret.len
return bf
}
return ret
}
// mClone is the mutable-clone: if Mut() set, it returns bf,
// otherwise bahaves as Clone()
func (bf *BitField) mClone() *BitField {
if bf.mutable {
return bf
}
return bf.Clone()
}
// Clone creates a copy of the bitfield and returns it
func (bf *BitField) Clone() *BitField {
ret := New(bf.len)
copy(ret.data, bf.data)
return ret
}
// Copy copies the content of BitField bf to dest.
// Returns false if the two bitfields differ in size, true otherwise
func (bf *BitField) Copy(dest *BitField) bool {
if bf.len != dest.len {
return false
}
copy(dest.data, bf.data)
return true
}
// Len returns the number of bits the BitField holds
func (bf *BitField) Len() int {
return bf.len
}
func (bf *BitField) posNormalize(pos int) int {
if bf.len == 0 {
return 0
}
for pos < 0 {
pos += bf.len
}
pos %= bf.len
return pos
}
func (bf *BitField) posToOffset(pos int) (index int, offset int) {
pos = bf.posNormalize(pos)
index = pos / 64
offset = pos % 64
return
}
// clearEnd zeroes the bits beyond Len() in-place
// The underlying BitField64 allocates space in 64bit increments
// and Len() might be smaller than the space allocated: it needs to be
// kept zeroed at all times to be consistent
func (bf *BitField) clearEnd() *BitField {
const n = 64
index, offset := bf.Len()/n, bf.Len()%n
// offset points to after the last element
delta := n - offset
bf.data[index] = bf.data[index].Shift(delta).Shift(-delta)
return bf
}
// Set sets the bit(s) at position pos. Mutable.
func (bf *BitField) Set(pos ...int) *BitField {
ret := bf.mClone()
for _, p := range pos {
index, offset := bf.posToOffset(p)
ret.data[index] = ret.data[index].Set(offset)
}
return ret
}
// SetAll sets all bits to 1. Mutable.
func (bf *BitField) SetAll() *BitField {
ret := bf.mClone()
for i := range ret.data {
ret.data[i] = ret.data[i].SetAll()
}
return ret.clearEnd()
}
// Clear clears the bit(s) at position pos. Mutable.
func (bf *BitField) Clear(pos ...int) *BitField {
ret := bf.mClone()
for _, p := range pos {
index, offset := bf.posToOffset(p)
ret.data[index] = ret.data[index].Clear(offset)
}
return ret
}
// ClearAll sets all bits to 1. Mutable.
func (bf *BitField) ClearAll() *BitField {
ret := bf.mClone()
for i := range ret.data {
ret.data[i] = ret.data[i].ClearAll()
}
return ret
}
// Get returns the bit (as a boolean) at position pos
func (bf *BitField) Get(pos int) bool {
index, offset := bf.posToOffset(pos)
return bf.data[index].Get(offset)
}
// Flip inverts the bit(s) at position pos. Mutable.
func (bf *BitField) Flip(pos ...int) *BitField {
ret := bf.mClone()
for _, p := range pos {
index, offset := ret.posToOffset(p)
ret.data[index] = ret.data[index].Flip(offset)
}
return ret
}
// OnesCount returns the number of bits set
func (bf *BitField) OnesCount() int {
count := 0
for i := range bf.data {
count += bf.data[i].OnesCount()
}
return count
}
const errLenOther = "Len() of bf and bfOther differ"
// And does a binary AND with bfOther. Panics if lengths differ. Mutable.
func (bf *BitField) And(bfOther *BitField) *BitField {
if bf.len != bfOther.len {
panic(errLenOther)
}
ret := bf.mClone()
for i := range ret.data {
ret.data[i] = ret.data[i].And(bfOther.data[i])
}
return ret
}
// Or does a binary OR with bfOther. Panics if lengths differ. Mutable.
func (bf *BitField) Or(bfOther *BitField) *BitField {
if bf.len != bfOther.len {
panic(errLenOther)
}
ret := bf.mClone()
for i := range ret.data {
ret.data[i] = ret.data[i].Or(bfOther.data[i])
}
return ret
}
// Not does a binary NOT (inverts all bits). Mutable.
func (bf *BitField) Not() *BitField {
ret := bf.mClone()
for i := range bf.data {
ret.data[i] = ret.data[i].Not()
}
return ret.clearEnd()
}
// Xor does a binary XOR with bfOther. Panics if lengths differ. Mutable.
func (bf *BitField) Xor(bfOther *BitField) *BitField {
if bf.len != bfOther.len {
panic(errLenOther)
}
ret := bf.mClone()
for i := range bf.data {
ret.data[i] = ret.data[i].Xor(bfOther.data[i])
}
return ret.clearEnd()
}
// Equal tells if two bitfields are equal or not
func (bf *BitField) Equal(bfOther *BitField) bool {
if bf.len != bfOther.len {
return false
}
for i := range bf.data {
if bf.data[i] != bfOther.data[i] {
return false
}
}
return true
}
// Shift shifts thes bitfield by count bits and returns it.
// If count is positive it shifts towards higher bit positions;
// If negative it shifts towards lower bit positions.
// Bits exiting at one end are discarded;
// bits entering at the other end are zeroed. Mutable.
func (bf *BitField) Shift(count int) *BitField {
ret := bf.mClone()
if count <= -bf.Len() || count >= bf.Len() {
return ret.ClearAll()
}
const n = 64
switch {
case count == 0:
return ret
case count > 0:
ix, delta := count/n, count%n
for i := len(ret.data) - 1; i >= 0; i-- {
tmp := New64()
if i-ix >= 0 {
tmp = ret.data[i-ix]
}
a, b := tmp.Shift2(delta)
ret.data[i] = a
if i+1 < len(bf.data) {
ret.data[i+1] = ret.data[i+1].Or(b)
}
}
ret.clearEnd()
case count < 0:
ix, delta := -count/n, -count%n
for i := 0; i < len(ret.data); i++ {
tmp := New64()
if i+ix < len(ret.data) {
tmp = ret.data[i+ix]
}
a, b := tmp.Shift2(-delta)
ret.data[i] = a
if i > 0 {
ret.data[i-1] = ret.data[i-1].Or(b)
}
}
}
return ret
}
// Mid returns counts bits from position pos as a new BitField
// Panics if count<0
func (bf *BitField) Mid(pos, count int) *BitField {
switch {
case count < 0:
panic("count cannot be negative")
case count == 0:
return New(0)
default:
if count > bf.Len() {
count = bf.Len()
}
pos = bf.posNormalize(pos)
return bf.Shift(-pos).resize(count)
}
}
// Left returns count bits in the range of [0,count-1] as a new BitField
// Panics if count<0
func (bf *BitField) Left(count int) *BitField {
return bf.Mid(0, count)
}
// Right returns count bits in the range of [63-count,63] as a new BitField
// Panics if count<0
func (bf *BitField) Right(count int) *BitField {
if count > bf.len {
count = bf.len
}
return bf.Mid(bf.Len()-count, count)
}
// Append appends 'other' BitField to the end
// A newly created bitfield will be returned
func (bf *BitField) Append(other *BitField) *BitField {
if other.Len() == 0 {
return bf.Clone()
}
len := bf.Len()
newLen := len + other.Len()
return other.
resize(newLen).
Shift(len).
Or(bf.resize(newLen))
}
// Rotate rotates by amount bits and returns it
// If amount>0 it rotates towards higher bit positions,
// otherwise it rotates towards lower bit positions. Mutable.
func (bf *BitField) Rotate(amount int) *BitField {
ret := bf.mClone()
if bf.len == 0 {
return ret
}
for amount < 0 {
amount += bf.len
}
amount %= bf.len
if amount%bf.len == 0 {
return ret
}
lh := bf.Left(bf.Len() - amount)
rh := bf.Right(amount)
rh.Append(lh).Copy(ret)
return ret
}
func (bf *BitField) String() string {
const n = 64
ret := make([]byte, bf.len)
for i := 0; i < len(bf.data); i++ {
s := bf.data[i].String()
for j := 0; j < len(s); j++ {
pos := i*n + j
if pos >= bf.len {
break
}
ret[pos] = s[j]
}
}
return string(ret)
}