-
Notifications
You must be signed in to change notification settings - Fork 0
/
bitstring.go
353 lines (296 loc) · 8.48 KB
/
bitstring.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 bitstring implements a fixed length bit string type and bit
// manipulation functions.
package bitstring
import (
"fmt"
"math/big"
"math/bits"
"math/rand"
"reflect"
"unsafe"
)
// Bitstring implements a fixed-length bit string.
//
// Internally, bits are packed into an array of machine word integers. This
// implementation makes more efficient use of space than the alternative
// approach of using an array of booleans.
type Bitstring struct {
// length in bits of the bit string
length int
// bits are packed in an array of uint64.
data []uint64
}
// New creates a bit string of the specified length (in bits) with all bits
// initially set to zero (off).
func New(length int) *Bitstring {
return &Bitstring{
length: length,
data: make([]uint64, (length+64-1)/64),
}
}
// Random creates a Bitstring of the length l in which each bit is assigned a
// random value using rng.
//
// Random randomly sets the uint32 values of the underlying slice, so it should
// be faster than creating a bit string and then randomly setting each
// individual bits.
func Random(length int, rng *rand.Rand) *Bitstring {
bs := New(length)
a := bs.data[:len(bs.data)] // remove bounds-checking
// Fill words with random values
for i := range a {
a[i] = uint64(rng.Uint64())
}
// If the last word is not fully utilised, zero any out-of-bounds bits.
// This is necessary because OnesCount and ZeroesCount count the
// out-of-bounds bits.
nused := bitoffset(uint64(length))
if nused != 0 {
mask := lomask(uint64(nused))
a[len(a)-1] &= mask
}
return bs
}
// NewFromString returns the corresponding Bitstring for the given string of 1s
// and 0s in big endian order.
func NewFromString(s string) (*Bitstring, error) {
bs := New(len(s))
for i, c := range s {
switch c {
case '0':
continue
case '1':
bs.SetBit(len(s) - i - 1)
default:
return nil, fmt.Errorf("illegal character at position %v: %#U", i, c)
}
}
return bs, nil
}
// Len returns the length if bs, that is the number of bits it contains.
func (bs *Bitstring) Len() int {
return int(bs.length)
}
// Data returns the bitstring underlying slice.
func (bs *Bitstring) Data() []uint64 {
return bs.data
}
// Bit returns a boolean indicating whether the bit at index i is set or not.
//
// If i is greater than the bitstring length, Bit will panic.
func (bs *Bitstring) Bit(i int) bool {
bs.mustExist(i)
w := wordoffset(uint64(i))
off := bitoffset(uint64(i))
mask := bitmask(off)
return (bs.data[w] & mask) != 0
}
// SetBit sets the bit at index i.
//
// If i is greater than the bitstring length, SetBit will panic.
func (bs *Bitstring) SetBit(i int) {
bs.mustExist(i)
w := wordoffset(uint64(i))
off := bitoffset(uint64(i))
bs.data[w] |= bitmask(off)
}
// ClearBit clears the bit at index i.
//
// If i is greater than the bitstring length, ClearBit will panic.
func (bs *Bitstring) ClearBit(i int) {
bs.mustExist(i)
w := wordoffset(uint64(i))
off := bitoffset(uint64(i))
bs.data[w] &= ^bitmask(off)
}
// FlipBit flips (i.e toggles) the bit at index i.
//
// If i is greater than the bitstring length, FlipBit will panic.
func (bs *Bitstring) FlipBit(i int) {
bs.mustExist(i)
w := wordoffset(uint64(i))
off := bitoffset(uint64(i))
bs.data[w] ^= (1 << off)
}
// OnesCount counts the number of one bits.
func (bs *Bitstring) OnesCount() int {
var count int
for _, x := range bs.data {
count += bits.OnesCount64(x)
}
return count
}
// ZeroesCount counts the number of zero bits.
func (bs *Bitstring) ZeroesCount() int {
return bs.length - bs.OnesCount()
}
func alignedRev(data []uint64) {
p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&data)).Data)
var buf []byte
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&buf))
hdr.Data = uintptr(p)
hdr.Len = len(data) * 8
hdr.Cap = len(data) * 8
// NOTE: we don't care about native endianness here since we're performing a
// byte-per-byte swap.
for i := 0; i < len(buf)/2; i++ {
buf[i], buf[len(buf)-i-1] = reverseLut[buf[len(buf)-i-1]], reverseLut[buf[i]]
}
}
// Reverse reverses all bits in-place.
func (bs *Bitstring) Reverse() {
// We first reverse the whole bitstring.
alignedRev(bs.data)
if bs.length%64 == 0 {
// No need for extra shifting.
return
}
rightShiftBits(bs.data, bitoffset(uint64(64-bs.length)))
}
// NewFromBig creates a new Bitstring using the absolute value of the big.Int
// bi.
//
// The number of bits of the new Bitstring depends on the number of significant
// bits in the binary representation of bi.
func NewFromBig(bi *big.Int) *Bitstring {
words := bi.Bits()
p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&words)).Data)
var bigData []uint64
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&bigData))
hdr.Data = uintptr(p)
hdr.Len = len(words)
hdr.Cap = hdr.Len
datalen := bi.BitLen() / 64
if bi.BitLen()%64 != 0 {
datalen++
}
bs := &Bitstring{
length: bi.BitLen(),
data: make([]uint64, datalen),
}
copy(bs.data, bigData)
return bs
}
// BigInt returns the big.Int representation of bs.
func (bs *Bitstring) BigInt() *big.Int {
cpy := bs.Clone()
p := unsafe.Pointer((*reflect.SliceHeader)(unsafe.Pointer(&cpy.data)).Data)
var words []big.Word
hdr := (*reflect.SliceHeader)(unsafe.Pointer(&words))
hdr.Data = uintptr(p)
hdr.Len = len(cpy.data) * (64 / wordsize)
hdr.Cap = hdr.Len
bint := new(big.Int)
bint.SetBits(words)
return bint
}
// String returns a string representation of bs in big endian order.
func (bs *Bitstring) String() string {
b := make([]byte, bs.length)
for i := 0; i < bs.length; i++ {
if bs.Bit(i) {
b[bs.length-1-i] = '1'
} else {
b[bs.length-1-i] = '0'
}
}
return string(b)
}
// Clone creates and returns a new Bitstring that is a clone of src.
func (bs *Bitstring) Clone() *Bitstring {
dst := make([]uint64, len(bs.data))
copy(dst, bs.data)
return &Bitstring{
length: bs.length,
data: dst,
}
}
// Copy copies a source Bitstring into a destination Bitstring, shrinking or
// expanding it if necessary.
func Copy(dst, src *Bitstring) {
switch {
case dst.length == src.length:
case dst.length < src.length:
dst.data = make([]uint64, len(src.data))
dst.length = src.length
case dst.length > src.length:
dst.data = dst.data[:len(src.data)]
dst.length = src.length
}
copy(dst.data, src.data)
}
// Equals returns true if bs and other have the same length and each bit are
// identical, or if bs and other both point to the same Bitstring instance (i.e
// pointer equality).
func (bs *Bitstring) Equals(other *Bitstring) bool {
switch {
case bs == other:
return true
case bs != nil && other == nil,
bs == nil && other != nil:
return false
case bs.length == other.length:
return u64cmp(bs.data, other.data)
}
return false
}
// LeadingZeroes returns the number of leading 0 bits in bs. (i.e the number of
// zeroes in the leftmost side of the string representation).
func (bs *Bitstring) LeadingZeroes() int {
bitoff := int(bitoffset(uint64(bs.length)))
start := len(bs.data) - 1
n := 0
for i := start; i >= 0; i-- {
leading := bits.LeadingZeros64(bs.data[i])
// We treat the first word separately if the bistring length is not a
// multiple of the wordsize because in this case we must omit the 'extra
// bits' from the count the count of leading zeroes.
if i == start && bitoff != 0 {
// Limit to 'off' the number of bits we count.
leading -= 64 - bitoff
n += leading
if leading != bitoff {
break // early exit if useful bits are not all 0s.
}
} else {
// Subsequent words
n += leading
if leading != 64 {
break
}
}
}
return n
}
// TrailingZeroes returns the number of leading 0 bits in bs. (i.e the number of
// zeroes in the rightmost side of the string representation).
func (bs *Bitstring) TrailingZeroes() int {
bitoff := int(bitoffset(uint64(bs.length)))
last := len(bs.data) - 1
n := 0
for i := 0; i < len(bs.data); i++ {
trailing := bits.TrailingZeros64(bs.data[i])
if i == last && bitoff != 0 && trailing == 64 {
// There's one specific case we need to take care of: if the last
// word if 0 and the bitstring length is not a multiple of the
// wordsize, then the effective number of trailing bits is not 64,
// we need to limit it to the number of useful bits only.
trailing = bitoff
}
n += trailing
if trailing != 64 {
break
}
}
return n
}
/*
// RotateLeft rotates the bitstring by (k mod len) bits.
func (bs *Bitstring) RotateLeft(k int) {
panic("unimplemented")
}
// RotateRight rotates the bitstring by (k mod len) bits.
func (bs *Bitstring) RotateRight(k int) {
panic("unimplemented")
}
*/