-
Notifications
You must be signed in to change notification settings - Fork 1
/
bitmap.go
68 lines (59 loc) · 1.08 KB
/
bitmap.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
package bitmap
import "fmt"
type Bitmap struct {
data []byte
size uint64
}
func NewBitmap(sz uint64) *Bitmap {
if sz+7 < sz {
panic(fmt.Sprintf("sz:%d overflow", sz))
}
sz = (sz + 7) / 8 * 8
return &Bitmap{
data: make([]byte, int(sz/8), int(sz/8)),
size: uint64(sz),
}
}
func (bm *Bitmap) Size() uint64 {
return bm.size
}
func (bm *Bitmap) IsSet(pos uint64) bool {
if pos >= bm.size {
return false
}
if bm.data[pos>>3]&(1<<(pos&0x7)) > 0 {
return true
}
return false
}
func (bm *Bitmap) Set(pos uint64) {
if pos >= bm.size {
return
}
bm.data[pos>>3] |= 1 << (pos & 0x7)
}
func (bm *Bitmap) UnSet(pos uint64) bool {
if pos >= bm.size {
return false
}
bm.data[pos>>3] ^= (1 << (pos & 0x7))
return true
}
func (bm *Bitmap) Resize(newSz uint64) {
if newSz+7 < newSz {
panic(fmt.Sprintf("newSz %d overflow", newSz))
}
newSz = (newSz + 7) / 8 * 8
// 等量扩容
if newSz == bm.size {
return
}
data := make([]byte, newSz/8, newSz/8)
copy(data, bm.data)
bm.data = data
bm.size = newSz
}
func (bm *Bitmap) Clear() {
bm.data = make([]byte, 0, 0)
bm.size = 0
}