Skip to content

Commit 17bc4a4

Browse files
committed
partialmessages: add basic bitmap package
The bitmap is probably the common case, so add library support for it.
1 parent b727a16 commit 17bc4a4

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

partialmessages/bitmap/bitmap.go

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
package bitmap
2+
3+
import (
4+
"math/bits"
5+
)
6+
7+
type Bitmap []byte
8+
9+
func NewBitmapWithOnesCount(n int) Bitmap {
10+
b := make(Bitmap, (n+7)/8)
11+
for i := range n {
12+
b.Set(i)
13+
}
14+
return b
15+
}
16+
17+
func Merge(left, right Bitmap) Bitmap {
18+
out := make(Bitmap, max(len(left), len(right)))
19+
out.Or(left)
20+
out.Or(right)
21+
return out
22+
}
23+
24+
func (b Bitmap) IsZero() bool {
25+
for i := range b {
26+
if b[i] != 0 {
27+
return false
28+
}
29+
}
30+
return true
31+
}
32+
33+
func (b Bitmap) OnesCount() int {
34+
var count int
35+
for i := range b {
36+
count += bits.OnesCount8(b[i])
37+
}
38+
return count
39+
}
40+
41+
func (b Bitmap) Set(index int) {
42+
for len(b)*8 <= index {
43+
b = append(b, 0)
44+
}
45+
b[index/8] |= 1 << (uint(index) % 8)
46+
}
47+
48+
func (b Bitmap) Get(index int) bool {
49+
if index >= len(b)*8 {
50+
return false
51+
}
52+
return b[index/8]&(1<<(uint(index%8))) != 0
53+
}
54+
55+
func (b Bitmap) Clear(index int) {
56+
if index >= len(b)*8 {
57+
return
58+
}
59+
b[index/8] &^= 1 << (uint(index) % 8)
60+
}
61+
62+
func (b Bitmap) And(other Bitmap) {
63+
for i := range min(len(b), len(other)) {
64+
b[i] &= other[i]
65+
}
66+
}
67+
68+
func (b Bitmap) Or(other Bitmap) {
69+
for i := range min(len(b), len(other)) {
70+
b[i] |= other[i]
71+
}
72+
}
73+
74+
func (b Bitmap) Xor(other Bitmap) {
75+
for i := range min(len(b), len(other)) {
76+
b[i] ^= other[i]
77+
}
78+
}
79+
80+
func (b Bitmap) Flip() {
81+
for i := range b {
82+
b[i] ^= 0xff
83+
}
84+
}

0 commit comments

Comments
 (0)