-
Notifications
You must be signed in to change notification settings - Fork 0
/
intfield.go
70 lines (58 loc) · 1.05 KB
/
intfield.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
69
70
package storage
import (
"fmt"
"github.com/RoaringBitmap/roaring"
)
// TODO: support negative ints
type intField struct {
max int
setBits *roaring.Bitmap
intBits []*roaring.Bitmap
}
func newIntField() *intField {
uf := &intField{
max: 0,
setBits: roaring.New(),
intBits: []*roaring.Bitmap{},
}
return uf
}
func (uf *intField) insert(id uint32, value any) error {
v, ok := value.(int)
if !ok {
return fmt.Errorf("cannot insert %T into int field", value)
}
if uf.max-1 < v {
uf.grow(v)
}
uf.setBits.Add(id)
for i, rb := range uf.intBits {
mask := 1 << i
if v&mask == mask {
rb.Add(id)
}
}
return nil
}
// could be optimized with math/bits hacks :)
func (uf *intField) grow(min int) {
for uf.max-1 < min {
uf.intBits = append(uf.intBits, roaring.New())
if uf.max == 0 {
uf.max = 1
}
uf.max <<= 1
}
}
func (uf *intField) get(id uint32) (any, error) {
if !uf.setBits.Contains(id) {
return nil, nil
}
var n int
for i, rb := range uf.intBits {
if rb.Contains(id) {
n += 1 << i
}
}
return n, nil
}