-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbitset.go
58 lines (48 loc) · 980 Bytes
/
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
package bitset
const word = uint64(64)
const logword = uint(6)
type Bitset struct {
length uint64
bits []uint64
}
func getSize(length uint64) uint64 {
return uint64((length + word - 1) / word)
}
func New(length uint64) *Bitset {
size := getSize(length)
return &Bitset{
length,
make([]uint64, size),
}
}
func getIndex(pos uint64) (q uint64, r uint) {
q = pos >> logword
r = uint(pos & (word - 1))
return
}
func (b *Bitset) Length() uint64 {
return b.length
}
func (b *Bitset) Get(pos uint64) bool {
q, r := getIndex(pos)
bit := (b.bits[q] >> r) & 1
return bit != 0
}
func (b *Bitset) Set(pos uint64) bool {
current := b.Get(pos)
q, r := getIndex(pos)
b.bits[q] |= (1 << r)
return current
}
func (b *Bitset) Clear(pos uint64) bool {
current := b.Get(pos)
q, r := getIndex(pos)
b.bits[q] &= ^(1 << r)
return current
}
func (b *Bitset) Flip(pos uint64) bool {
current := b.Get(pos)
q, r := getIndex(pos)
b.bits[q] ^= (1 << r)
return current
}