forked from sbilly/go-windivert2
/
node32.go
439 lines (361 loc) · 10.4 KB
/
node32.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
// Package numtree implements radix tree data structure for 32 and 64-bit unsigned integets. Copy-on-write is used for any tree modification so old root doesn't see any change happens with tree.
// https://github.com/infobloxopen/go-trees/tree/master/numtree
package iptree
import (
"fmt"
"math/bits"
)
// Key32BitSize is an alias for bitsize of 32-bit radix tree's key.
const Key32BitSize = 32
var (
masks32 = []uint32{
0x00000000, 0x80000000, 0xc0000000, 0xe0000000,
0xf0000000, 0xf8000000, 0xfc000000, 0xfe000000,
0xff000000, 0xff800000, 0xffc00000, 0xffe00000,
0xfff00000, 0xfff80000, 0xfffc0000, 0xfffe0000,
0xffff0000, 0xffff8000, 0xffffc000, 0xffffe000,
0xfffff000, 0xfffff800, 0xfffffc00, 0xfffffe00,
0xffffff00, 0xffffff80, 0xffffffc0, 0xffffffe0,
0xfffffff0, 0xfffffff8, 0xfffffffc, 0xfffffffe,
0xffffffff}
)
// Node32 is an element of radix tree with 32-bit unsigned integer as a key.
type Node32 struct {
// Key stores key for current node.
Key uint32
// Bits is a number of significant bits in Key.
Bits uint8
// Leaf indicates if the node is leaf node and contains any data in Value.
Leaf bool
// Value contains data associated with key.
Value interface{}
chld [2]*Node32
}
// Dot dumps tree to Graphviz .dot format
func (n *Node32) Dot() string {
body := ""
// Iterate all nodes using breadth-first search algorithm.
i := 0
queue := []*Node32{n}
for len(queue) > 0 {
c := queue[0]
body += fmt.Sprintf("N%d %s\n", i, c.dotString())
if c != nil && (c.chld[0] != nil || c.chld[1] != nil) {
// Children for current node if any always go to the end of the queue
// so we can know their indices using current queue length.
body += fmt.Sprintf("N%d -> { N%d N%d }\n", i, i+len(queue), i+len(queue)+1)
queue = append(append(queue, c.chld[0]), c.chld[1])
}
queue = queue[1:]
i++
}
return "digraph d {\n" + body + "}\n"
}
// Insert puts new leaf to radix tree and returns pointer to new root. The method uses copy on write strategy so old root doesn't see the change.
func (n *Node32) Insert(key uint32, bits int, value interface{}) *Node32 {
// Adjust bits.
if bits < 0 {
bits = 0
} else if bits > Key32BitSize {
bits = Key32BitSize
}
return n.insert(newNode32(key, uint8(bits), true, value))
}
// InplaceInsert puts new leaf to radix tree (or replaces value in existing one). The method inserts data directly to current tree so make sure you have exclusive access to it.
func (n *Node32) InplaceInsert(key uint32, bits int, value interface{}) *Node32 {
// Adjust bits.
if bits < 0 {
bits = 0
} else if bits > Key32BitSize {
bits = Key32BitSize
}
return n.inplaceInsert(key, uint8(bits), value)
}
// Enumerate returns channel which is populated by nodes with data in order of their keys.
func (n *Node32) Enumerate() chan *Node32 {
ch := make(chan *Node32)
go func() {
defer close(ch)
// If tree is empty -
if n == nil {
// return nothing.
return
}
n.enumerate(ch)
}()
return ch
}
// Match locates node which key is equal to or "contains" the key passed as argument.
func (n *Node32) Match(key uint32, bits int) (interface{}, bool) {
// If tree is empty -
if n == nil {
// report nothing.
return n, false
}
// Adjust bits.
if bits < 0 {
bits = 0
} else if bits > Key32BitSize {
bits = Key32BitSize
}
r := n.match(key, uint8(bits))
if r == nil {
return nil, false
}
return r.Value, true
}
// ExactMatch locates node which exactly matches given key.
func (n *Node32) ExactMatch(key uint32, bits int) (interface{}, bool) {
// If tree is empty -
if n == nil {
// report nothing.
return n, false
}
// Adjust bits.
if bits < 0 {
bits = 0
} else if bits > Key32BitSize {
bits = Key32BitSize
}
r := n.exactMatch(key, uint8(bits))
if r == nil {
return nil, false
}
return r.Value, true
}
// Delete removes subtree which is contained by given key. The method uses copy on write strategy.
func (n *Node32) Delete(key uint32, bits int) (*Node32, bool) {
// If tree is empty -
if n == nil {
// report nothing.
return n, false
}
// Adjust bits.
if bits < 0 {
bits = 0
} else if bits > Key32BitSize {
bits = Key32BitSize
}
return n.del(key, uint8(bits))
}
func (n *Node32) dotString() string {
if n == nil {
return "[label=\"nil\"]"
}
if n.Leaf {
v := fmt.Sprintf("%q", fmt.Sprintf("%#v", n.Value))
return fmt.Sprintf("[label=\"k: %08x, b: %d, v: \\\"%s\\\"\"]", n.Key, n.Bits, v[1:len(v)-1])
}
return fmt.Sprintf("[label=\"k: %08x, b: %d\"]", n.Key, n.Bits)
}
func (n *Node32) insert(c *Node32) *Node32 {
if n == nil {
return c
}
// Find number of common most significant bits (NCSB):
// 1. xor operation puts zeroes at common bits;
// 2. or masks put ones so that zeroes can't go after smaller number of significant bits (NSB)
// 3. count of leading zeroes gives number of common bits
bits := uint8(bits.LeadingZeros32((n.Key ^ c.Key) | ^masks32[n.Bits] | ^masks32[c.Bits]))
// There are three cases possible:
// - NCSB less than number of significant bits (NSB) of current tree node:
if bits < n.Bits {
// (branch for current tree node is determined by a bit right after the last common bit)
branch := (n.Key >> (Key32BitSize - 1 - bits)) & 1
// - NCSB equals to NSB of candidate node:
if bits == c.Bits {
// make new root from the candidate and put current node to one of its branch;
c.chld[branch] = n
return c
}
// - NCSB less than NSB of candidate node (it can't be greater because bits after NSB don't count):
// make new root (non-leaf node)
m := newNode32(c.Key&masks32[bits], bits, false, nil)
// with current tree node at one of branches
m.chld[branch] = n
// and the candidate at the other.
m.chld[1-branch] = c
return m
}
// - keys are equal (NCSB not less than NSB of current tree node and both numbers are equal):
if c.Bits == n.Bits {
// replace current node with the candidate.
c.chld = n.chld
return c
}
// - current tree node contains candidate node:
// make new root as a copy of current tree node;
m := newNode32(n.Key, n.Bits, n.Leaf, n.Value)
m.chld = n.chld
// (branch for the candidate is determined by a bit right after the last common bit)
branch := (c.Key >> (Key32BitSize - 1 - bits)) & 1
// insert it to correct branch.
m.chld[branch] = m.chld[branch].insert(c)
return m
}
func (n *Node32) inplaceInsert(key uint32, sbits uint8, value interface{}) *Node32 {
var (
p *Node32
branch uint32
)
r := n
for n != nil {
cbits := uint8(bits.LeadingZeros32((n.Key ^ key) | ^masks32[n.Bits] | ^masks32[sbits]))
if cbits < n.Bits {
pBranch := branch
branch = (n.Key >> (Key32BitSize - 1 - cbits)) & 1
var m *Node32
if cbits == sbits {
m = newNode32(key, sbits, true, value)
m.chld[branch] = n
} else {
m = newNode32(key&masks32[cbits], cbits, false, nil)
m.chld[1-branch] = newNode32(key, sbits, true, value)
}
m.chld[branch] = n
if p == nil {
r = m
} else {
p.chld[pBranch] = m
}
return r
}
if sbits == n.Bits {
n.Key = key
n.Leaf = true
n.Value = value
return r
}
p = n
branch = (key >> (Key32BitSize - 1 - cbits)) & 1
n = n.chld[branch]
}
n = newNode32(key, sbits, true, value)
if p == nil {
return n
}
p.chld[branch] = n
return r
}
func (n *Node32) enumerate(ch chan *Node32) {
// Implemented by depth-first search.
if n.Leaf {
ch <- n
}
if n.chld[0] != nil {
n.chld[0].enumerate(ch)
}
if n.chld[1] != nil {
n.chld[1].enumerate(ch)
}
}
func (n *Node32) match(key uint32, bits uint8) *Node32 {
// If can't be contained in current root node -
if n.Bits > bits {
// report nothing.
return nil
}
// If NSB of current tree node is the same as key has -
if n.Bits == bits {
// return current node only if it contains data (leaf node) and masked keys are equal.
if n.Leaf && (n.Key^key)&masks32[n.Bits] == 0 {
return n
}
return nil
}
// If key can be contained by current tree node -
if (n.Key^key)&masks32[n.Bits] != 0 {
// but it isn't report nothing.
return nil
}
// Otherwise jump to branch by key bit right after NSB of current tree node
c := n.chld[(key>>(Key32BitSize-1-n.Bits))&1]
if c != nil {
// and check if child on the branch has anything.
r := c.match(key, bits)
if r != nil {
return r
}
}
// If nothing matches check if current node contains any data.
if n.Leaf {
return n
}
return nil
}
func (n *Node32) exactMatch(key uint32, bits uint8) *Node32 {
// If can't be contained in current root node -
if n.Bits > bits {
// report nothing.
return nil
}
// If NSB of current tree node is the same as key has -
if n.Bits == bits {
// return current node only if it contains data (leaf node) and masked keys are equal.
if n.Leaf && (n.Key^key)&masks32[n.Bits] == 0 {
return n
}
return nil
}
// If key can be contained by current tree node -
if (n.Key^key)&masks32[n.Bits] != 0 {
// but it isn't report nothing.
return nil
}
// Otherwise jump to branch by key bit right after NSB of current tree node
c := n.chld[(key>>(Key32BitSize-1-n.Bits))&1]
if c != nil {
// and check if child on the branch has anything.
r := c.exactMatch(key, bits)
if r != nil {
return r
}
}
return nil
}
func (n *Node32) del(key uint32, bits uint8) (*Node32, bool) {
// If key can contain current tree node -
if bits <= n.Bits {
// report empty new tree and put deletion mark if it contains indeed.
if (n.Key^key)&masks32[bits] == 0 {
return nil, true
}
return n, false
}
// If key can be contained by current tree node -
if (n.Key^key)&masks32[n.Bits] != 0 {
// but it isn't report nothing.
return n, false
}
// Otherwise jump to branch by key bit right after NSB of current tree node
branch := (key >> (Key32BitSize - 1 - n.Bits)) & 1
c := n.chld[branch]
if c == nil {
// report nothing if the branch is empty.
return n, false
}
// Try to remove from subtree
c, ok := c.del(key, bits)
if !ok {
// and report nothing if nothing has been deleted.
return n, false
}
// If child of non-leaf node has been completely deleted -
if c == nil && !n.Leaf {
// drop the node.
return n.chld[1-branch], true
}
// If deletion happens inside the branch then copy current node.
m := newNode32(n.Key, n.Bits, n.Leaf, n.Value)
m.chld = n.chld
// Replace changed child with new one and return new root with deletion mark set.
m.chld[branch] = c
return m, true
}
func newNode32(key uint32, bits uint8, leaf bool, value interface{}) *Node32 {
return &Node32{
Key: key,
Bits: bits,
Leaf: leaf,
Value: value}
}