-
Notifications
You must be signed in to change notification settings - Fork 4
/
bits.go
66 lines (59 loc) · 1010 Bytes
/
bits.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
package hamt
import "math/bits"
func rangedInt(p []byte, from, to int) int {
if from > to || from < 0 || to < 0 {
panic("invalid range")
}
// Skip the leading unused bytes.
for from >= 8 {
p = p[1:]
from -= 8
to -= 8
}
result := 0
for to > 0 {
b0 := p[0]
if from > 0 {
// Remove remaining leading bits.
b0 = (b0 << from) >> from
from = 0
}
if to < 8 {
// Remove the trailing bits we don't want.
b0 >>= (8 - to)
result = result << to
} else {
result = result << 8
}
result |= int(b0)
p = p[1:]
to -= 8
}
return result
}
func bitsetGet(p []byte, i int) bool {
return p[i/8]&(1<<(7-i%8)) != 0
}
func bitsetSet(p []byte, i int) {
n := p[i/8]
n |= 1 << (7 - i%8)
p[i/8] = n
}
func bitsetClear(p []byte, i int) {
n := p[i/8]
n &^= 1 << (7 - i%8)
p[i/8] = n
}
func onesCountRange(p []byte, to int) int {
count := 0
for to > 0 {
b := p[0]
if to < 8 {
b >>= 8 - to
}
count += bits.OnesCount8(b)
to -= 8
p = p[1:]
}
return count
}