...
1 package descriptor
2
3 import "math/bits"
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24 type Table[Key ~int32, Item any] struct {
25 masks []uint64
26 items []Item
27 }
28
29
30 func (t *Table[Key, Item]) Len() (n int) {
31
32
33
34 for _, mask := range t.masks {
35 n += bits.OnesCount64(mask)
36 }
37 return n
38 }
39
40
41
42 func (t *Table[Key, Item]) grow(n int) {
43
44
45 n = (n*64 + 63) / 64
46
47 if n > len(t.masks) {
48 masks := make([]uint64, n)
49 copy(masks, t.masks)
50
51 items := make([]Item, n*64)
52 copy(items, t.items)
53
54 t.masks = masks
55 t.items = items
56 }
57 }
58
59
60
61
62
63
64 func (t *Table[Key, Item]) Insert(item Item) (key Key, ok bool) {
65 offset := 0
66 insert:
67
68
69
70 for index, mask := range t.masks[offset:] {
71 if ^mask != 0 {
72 shift := bits.TrailingZeros64(^mask)
73 index += offset
74 key = Key(index)*64 + Key(shift)
75 t.items[key] = item
76 t.masks[index] = mask | uint64(1<<shift)
77 return key, key >= 0
78 }
79 }
80
81 offset = len(t.masks)
82 n := 2 * len(t.masks)
83 if n == 0 {
84 n = 1
85 }
86
87 t.grow(n)
88 goto insert
89 }
90
91
92 func (t *Table[Key, Item]) Lookup(key Key) (item Item, found bool) {
93 if key < 0 {
94 return
95 }
96 if i := int(key); i >= 0 && i < len(t.items) {
97 index := uint(key) / 64
98 shift := uint(key) % 64
99 if (t.masks[index] & (1 << shift)) != 0 {
100 item, found = t.items[i], true
101 }
102 }
103 return
104 }
105
106
107
108 func (t *Table[Key, Item]) InsertAt(item Item, key Key) bool {
109 if key < 0 {
110 return false
111 }
112 if diff := int(key) - t.Len(); diff > 0 {
113 t.grow(diff)
114 }
115 index := uint(key) / 64
116 shift := uint(key) % 64
117 t.masks[index] |= 1 << shift
118 t.items[key] = item
119 return true
120 }
121
122
123 func (t *Table[Key, Item]) Delete(key Key) {
124 if key < 0 {
125 return
126 }
127 if index, shift := key/64, key%64; int(index) < len(t.masks) {
128 mask := t.masks[index]
129 if (mask & (1 << shift)) != 0 {
130 var zero Item
131 t.items[key] = zero
132 t.masks[index] = mask & ^uint64(1<<shift)
133 }
134 }
135 }
136
137
138
139 func (t *Table[Key, Item]) Range(f func(Key, Item) bool) {
140 for i, mask := range t.masks {
141 if mask == 0 {
142 continue
143 }
144 for j := Key(0); j < 64; j++ {
145 if (mask & (1 << j)) == 0 {
146 continue
147 }
148 if key := Key(i)*64 + j; !f(key, t.items[key]) {
149 return
150 }
151 }
152 }
153 }
154
155
156 func (t *Table[Key, Item]) Reset() {
157 for i := range t.masks {
158 t.masks[i] = 0
159 }
160 var zero Item
161 for i := range t.items {
162 t.items[i] = zero
163 }
164 }
165
View as plain text