-
-
Notifications
You must be signed in to change notification settings - Fork 36
/
bitmask.go
52 lines (45 loc) · 1.03 KB
/
bitmask.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
package main
import "sync"
import "github.com/tmthrgd/go-popcount"
// Bitmask - simple bitmask data structire based on a map
type Bitmask struct {
I map[uint64]uint64
mutex *sync.RWMutex
}
// Has - basic get/set methods
func (b *Bitmask) Has(val int64) bool {
var v = uint64(val)
b.mutex.RLock()
defer b.mutex.RUnlock()
return (b.I[v/64] & (1 << (v % 64))) != 0
}
// Insert - basic get/set methods
func (b *Bitmask) Insert(val int64) {
var v = uint64(val)
b.mutex.Lock()
defer b.mutex.Unlock()
b.I[v/64] |= (1 << (v % 64))
}
// Len - total elements in mask (non performant!)
func (b *Bitmask) Len() uint64 {
var l uint64
b.mutex.RLock()
defer b.mutex.RUnlock()
for _, v := range b.I {
l += popcount.CountSlice64([]uint64{v})
}
return l
}
// Empty - return true if bitmask is entirely empty
func (b *Bitmask) Empty() bool {
b.mutex.RLock()
defer b.mutex.RUnlock()
return len(b.I) == 0
}
// NewBitMask - constructor
func NewBitMask() *Bitmask {
return &Bitmask{
I: make(map[uint64]uint64),
mutex: &sync.RWMutex{},
}
}