forked from kentik/patricia
/
tree_v4.go
656 lines (563 loc) · 17.5 KB
/
tree_v4.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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
package float32_tree
import (
"fmt"
"github.com/gcla/patricia"
)
// TreeV4 is an IP Address patricia tree
type TreeV4 struct {
nodes []treeNodeV4 // root is always at [1] - [0] is unused
availableIndexes []uint // a place to store node indexes that we deleted, and are available
tags map[uint64]float32
}
// NewTreeV4 returns a new Tree
func NewTreeV4() *TreeV4 {
return &TreeV4{
nodes: make([]treeNodeV4, 2, 2), // index 0 is skipped, 1 is root
availableIndexes: make([]uint, 0),
tags: make(map[uint64]float32),
}
}
// Clone creates an identical copy of the tree
// - Note: the items in the tree are not deep copied
func (t *TreeV4) Clone() *TreeV4 {
ret := &TreeV4{
nodes: make([]treeNodeV4, len(t.nodes), cap(t.nodes)),
availableIndexes: make([]uint, len(t.availableIndexes), cap(t.availableIndexes)),
tags: make(map[uint64]float32),
}
for i := range t.nodes {
ret.nodes[i] = t.nodes[i]
}
for i := range t.availableIndexes {
ret.availableIndexes[i] = t.availableIndexes[i]
}
for k, v := range t.tags {
ret.tags[k] = v
}
return ret
}
// add a tag to the node at the input index, storing it in the first position if 'replaceFirst' is true
// - if matchFunc is non-nil, will enforce uniqueness at this node
// - returns whether the tag count was increased
func (t *TreeV4) addTag(tag float32, nodeIndex uint, matchFunc MatchesFunc, replaceFirst bool) bool {
ret := true
if replaceFirst {
if t.nodes[nodeIndex].TagCount == 0 {
t.nodes[nodeIndex].TagCount = 1
} else {
ret = false
}
t.tags[(uint64(nodeIndex) << 32)] = tag
} else {
key := (uint64(nodeIndex) << 32)
tagCount := t.nodes[nodeIndex].TagCount
if matchFunc != nil {
// need to check if this value already exists
for i := 0; i < tagCount; i++ {
if matchFunc(t.tags[key+uint64(i)], tag) {
return false
}
}
}
t.tags[key+(uint64(tagCount))] = tag
t.nodes[nodeIndex].TagCount++
}
return ret
}
func (t *TreeV4) tagsForNode(nodeIndex uint) []float32 {
// TODO: clean up the typing in here, between uint, uint64
tagCount := t.nodes[nodeIndex].TagCount
ret := make([]float32, tagCount)
key := uint64(nodeIndex) << 32
for i := 0; i < tagCount; i++ {
ret[i] = t.tags[key+uint64(i)]
}
return ret
}
func (t *TreeV4) moveTags(fromIndex uint, toIndex uint) {
tagCount := t.nodes[fromIndex].TagCount
fromKey := uint64(fromIndex) << 32
toKey := uint64(toIndex) << 32
for i := 0; i < tagCount; i++ {
t.tags[toKey+uint64(i)] = t.tags[fromKey+uint64(i)]
delete(t.tags, fromKey+uint64(i))
}
t.nodes[toIndex].TagCount += t.nodes[fromIndex].TagCount
t.nodes[fromIndex].TagCount = 0
}
func (t *TreeV4) firstTagForNode(nodeIndex uint) float32 {
return t.tags[(uint64(nodeIndex) << 32)]
}
// delete tags at the input node, returning how many were deleted, and how many are left
func (t *TreeV4) deleteTag(nodeIndex uint, matchTag float32, matchFunc MatchesFunc) (int, int) {
// TODO: this could be done much more efficiently
// get tags
tags := t.tagsForNode(nodeIndex)
// delete tags
for i := 0; i < t.nodes[nodeIndex].TagCount; i++ {
delete(t.tags, (uint64(nodeIndex)<<32)+uint64(i))
}
t.nodes[nodeIndex].TagCount = 0
// put them back
deleteCount := 0
keepCount := 0
for _, tag := range tags {
if matchFunc(tag, matchTag) {
deleteCount++
} else {
// doesn't match - get to keep it
t.addTag(tag, nodeIndex, matchFunc, false)
keepCount++
}
}
return deleteCount, keepCount
}
// Set the single value for a node - overwrites what's there
// Returns whether the tag count at this address was increased, and how many tags at this address
func (t *TreeV4) Set(address patricia.IPv4Address, tag float32) (bool, int, error) {
return t.add(address, tag, nil, true)
}
// Add adds a tag to the tree
// - if matchFunc is non-nil, it will be used to ensure uniqueness at this node
// - returns whether the tag count at this address was increased, and how many tags at this address
func (t *TreeV4) Add(address patricia.IPv4Address, tag float32, matchFunc MatchesFunc) (bool, int, error) {
return t.add(address, tag, matchFunc, false)
}
// add a tag to the tree, optionally as the single value
// - overwrites the first value in the list if 'replaceFirst' is true
// - returns whether the tag count was increased, and the number of tags at this address
func (t *TreeV4) add(address patricia.IPv4Address, tag float32, matchFunc MatchesFunc, replaceFirst bool) (bool, int, error) {
// make sure we have more than enough capacity before we start adding to the tree, which invalidates pointers into the array
if (len(t.availableIndexes) + cap(t.nodes)) < (len(t.nodes) + 10) {
temp := make([]treeNodeV4, len(t.nodes), (cap(t.nodes)+1)*2)
copy(temp, t.nodes)
t.nodes = temp
}
root := &t.nodes[1]
// handle root tags
if address.Length == 0 {
countIncreased := t.addTag(tag, 1, matchFunc, replaceFirst)
return countIncreased, t.nodes[1].TagCount, nil
}
// root node doesn't have any prefix, so find the starting point
nodeIndex := uint(0)
parent := root
if !address.IsLeftBitSet() {
if root.Left == 0 {
newNodeIndex := t.newNode(address, address.Length)
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
root.Left = newNodeIndex
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
nodeIndex = root.Left
} else {
if root.Right == 0 {
newNodeIndex := t.newNode(address, address.Length)
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
root.Right = newNodeIndex
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
nodeIndex = root.Right
}
for {
if nodeIndex == 0 {
panic("Trying to traverse nodeIndex=0")
}
node := &t.nodes[nodeIndex]
if node.prefixLength == 0 {
panic("Reached a node with no prefix")
}
matchCount := uint(node.MatchCount(address))
if matchCount == 0 {
panic(fmt.Sprintf("Should not have traversed to a node with no prefix match - node prefix length: %d; address prefix length: %d", node.prefixLength, address.Length))
}
if matchCount == address.Length {
// all the bits in the address matched
if matchCount == node.prefixLength {
// the whole prefix matched - we're done!
countIncreased := t.addTag(tag, nodeIndex, matchFunc, replaceFirst)
return countIncreased, t.nodes[nodeIndex].TagCount, nil
}
// the input address is shorter than the match found - need to create a new, intermediate parent
newNodeIndex := t.newNode(address, address.Length)
newNode := &t.nodes[newNodeIndex]
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
// the existing node loses those matching bits, and becomes a child of the new node
// shift
node.ShiftPrefix(matchCount)
if !node.IsLeftBitSet() {
newNode.Left = nodeIndex
} else {
newNode.Right = nodeIndex
}
// now give this new node a home
if parent.Left == nodeIndex {
parent.Left = newNodeIndex
} else {
if parent.Right != nodeIndex {
panic("node isn't left or right parent - should be impossible! (1)")
}
parent.Right = newNodeIndex
}
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
if matchCount == node.prefixLength {
// partial match - we have to keep traversing
// chop off what's matched so far
address.ShiftLeft(matchCount)
if !address.IsLeftBitSet() {
if node.Left == 0 {
// nowhere else to go - create a new node here
newNodeIndex := t.newNode(address, address.Length)
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
node.Left = newNodeIndex
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
// there's a node to the left - traverse it
parent = node
nodeIndex = node.Left
continue
}
// node didn't belong on the left, so it belongs on the right
if node.Right == 0 {
// nowhere else to go - create a new node here
newNodeIndex := t.newNode(address, address.Length)
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
node.Right = newNodeIndex
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
// there's a node to the right - traverse it
parent = node
nodeIndex = node.Right
continue
}
// partial match with this node - need to split this node
newCommonParentNodeIndex := t.newNode(address, matchCount)
newCommonParentNode := &t.nodes[newCommonParentNodeIndex]
// shift
address.ShiftLeft(matchCount)
newNodeIndex := t.newNode(address, address.Length)
countIncreased := t.addTag(tag, newNodeIndex, matchFunc, replaceFirst)
// see where the existing node fits - left or right
node.ShiftPrefix(matchCount)
if !node.IsLeftBitSet() {
newCommonParentNode.Left = nodeIndex
newCommonParentNode.Right = newNodeIndex
} else {
newCommonParentNode.Right = nodeIndex
newCommonParentNode.Left = newNodeIndex
}
// now determine where the new node belongs
if parent.Left == nodeIndex {
parent.Left = newCommonParentNodeIndex
} else {
if parent.Right != nodeIndex {
panic("node isn't left or right parent - should be impossible! (2)")
}
parent.Right = newCommonParentNodeIndex
}
return countIncreased, t.nodes[newNodeIndex].TagCount, nil
}
}
// Delete a tag from the tree if it matches matchVal, as determined by matchFunc. Returns how many tags are removed
func (t *TreeV4) Delete(address patricia.IPv4Address, matchFunc MatchesFunc, matchVal float32) (int, error) {
// traverse the tree, finding the node and its parent
root := &t.nodes[1]
var parentIndex uint
var parent *treeNodeV4
var targetNode *treeNodeV4
var targetNodeIndex uint
if address.Length == 0 {
// caller just looking for root tags
targetNode = root
targetNodeIndex = 1
} else {
nodeIndex := uint(0)
parentIndex = 1
parent = root
if !address.IsLeftBitSet() {
nodeIndex = root.Left
} else {
nodeIndex = root.Right
}
// traverse the tree
for {
if nodeIndex == 0 {
return 0, nil
}
node := &t.nodes[nodeIndex]
matchCount := node.MatchCount(address)
if matchCount < node.prefixLength {
// didn't match the entire node - we're done
return 0, nil
}
if matchCount == address.Length {
// exact match - we're done
targetNode = node
targetNodeIndex = nodeIndex
break
}
// there's still more address - keep traversing
parentIndex = nodeIndex
parent = node
address.ShiftLeft(matchCount)
if !address.IsLeftBitSet() {
nodeIndex = node.Left
} else {
nodeIndex = node.Right
}
}
}
if targetNode == nil || targetNode.TagCount == 0 {
// no tags found
return 0, nil
}
// delete matching tags
deleteCount, remainingTagCount := t.deleteTag(targetNodeIndex, matchVal, matchFunc)
if remainingTagCount > 0 {
// target node still has tags - we're not deleting it
return deleteCount, nil
}
if targetNodeIndex == 1 {
// can't delete the root node
return deleteCount, nil
}
// compact the tree, if possible
if targetNode.Left != 0 && targetNode.Right != 0 {
// target has two children - nothing we can do - not deleting the node
return deleteCount, nil
} else if targetNode.Left != 0 {
// target node only has only left child
if parent.Left == targetNodeIndex {
parent.Left = targetNode.Left
} else {
parent.Right = targetNode.Left
}
// need to update the child node prefix to include target node's
tmpNode := &t.nodes[targetNode.Left]
tmpNode.MergeFromNodes(targetNode, tmpNode)
} else if targetNode.Right != 0 {
// target node has only right child
if parent.Left == targetNodeIndex {
parent.Left = targetNode.Right
} else {
parent.Right = targetNode.Right
}
// need to update the child node prefix to include target node's
tmpNode := &t.nodes[targetNode.Right]
tmpNode.MergeFromNodes(targetNode, tmpNode)
} else {
// target node has no children - straight-up remove this node
if parent.Left == targetNodeIndex {
parent.Left = 0
if parentIndex > 1 && parent.TagCount == 0 && parent.Right != 0 {
// parent isn't root, has no tags, and there's a sibling - merge sibling into parent
siblingIndexToDelete := parent.Right
tmpNode := &t.nodes[siblingIndexToDelete]
parent.MergeFromNodes(parent, tmpNode)
// move tags
t.moveTags(siblingIndexToDelete, parentIndex)
// parent now gets target's sibling's children
parent.Left = t.nodes[siblingIndexToDelete].Left
parent.Right = t.nodes[siblingIndexToDelete].Right
t.availableIndexes = append(t.availableIndexes, siblingIndexToDelete)
}
} else {
parent.Right = 0
if parentIndex > 1 && parent.TagCount == 0 && parent.Left != 0 {
// parent isn't root, has no tags, and there's a sibling - merge sibling into parent
siblingIndexToDelete := parent.Left
tmpNode := &t.nodes[siblingIndexToDelete]
parent.MergeFromNodes(parent, tmpNode)
// move tags
t.moveTags(siblingIndexToDelete, parentIndex)
// parent now gets target's sibling's children
parent.Right = t.nodes[parent.Left].Right
parent.Left = t.nodes[parent.Left].Left
t.availableIndexes = append(t.availableIndexes, siblingIndexToDelete)
}
}
}
targetNode.Left = 0
targetNode.Right = 0
t.availableIndexes = append(t.availableIndexes, targetNodeIndex)
return deleteCount, nil
}
// FindTagsWithFilter finds all matching tags that passes the filter function
func (t *TreeV4) FindTagsWithFilter(address patricia.IPv4Address, filterFunc FilterFunc) ([]float32, error) {
root := &t.nodes[1]
if filterFunc == nil {
return t.FindTags(address)
}
var matchCount uint
ret := make([]float32, 0)
if root.TagCount > 0 {
for _, tag := range t.tagsForNode(1) {
if filterFunc(tag) {
ret = append(ret, tag)
}
}
}
if address.Length == 0 {
// caller just looking for root tags
return ret, nil
}
var nodeIndex uint
if !address.IsLeftBitSet() {
nodeIndex = root.Left
} else {
nodeIndex = root.Right
}
// traverse the tree
count := 0
for {
count++
if nodeIndex == 0 {
return ret, nil
}
node := &t.nodes[nodeIndex]
matchCount = node.MatchCount(address)
if matchCount < node.prefixLength {
// didn't match the entire node - we're done
return ret, nil
}
// matched the full node - get its tags, then chop off the bits we've already matched and continue
if node.TagCount > 0 {
for _, tag := range t.tagsForNode(nodeIndex) {
if filterFunc(tag) {
ret = append(ret, tag)
}
}
}
if matchCount == address.Length {
// exact match - we're done
return ret, nil
}
// there's still more address - keep traversing
address.ShiftLeft(matchCount)
if !address.IsLeftBitSet() {
nodeIndex = node.Left
} else {
nodeIndex = node.Right
}
}
}
// FindTags finds all matching tags that passes the filter function
func (t *TreeV4) FindTags(address patricia.IPv4Address) ([]float32, error) {
var matchCount uint
root := &t.nodes[1]
ret := make([]float32, 0)
if root.TagCount > 0 {
ret = append(ret, t.tagsForNode(1)...)
}
if address.Length == 0 {
// caller just looking for root tags
return ret, nil
}
var nodeIndex uint
if !address.IsLeftBitSet() {
nodeIndex = root.Left
} else {
nodeIndex = root.Right
}
// traverse the tree
count := 0
for {
count++
if nodeIndex == 0 {
return ret, nil
}
node := &t.nodes[nodeIndex]
matchCount = node.MatchCount(address)
if matchCount < node.prefixLength {
// didn't match the entire node - we're done
return ret, nil
}
// matched the full node - get its tags, then chop off the bits we've already matched and continue
if node.TagCount > 0 {
ret = append(ret, t.tagsForNode(nodeIndex)...)
}
if matchCount == address.Length {
// exact match - we're done
return ret, nil
}
// there's still more address - keep traversing
address.ShiftLeft(matchCount)
if !address.IsLeftBitSet() {
nodeIndex = node.Left
} else {
nodeIndex = node.Right
}
}
}
// FindDeepestTag finds a tag at the deepest level in the tree, representing the closest match
// - if that target node has multiple tags, the first in the list is returned
func (t *TreeV4) FindDeepestTag(address patricia.IPv4Address) (bool, float32, error) {
root := &t.nodes[1]
var found bool
var ret float32
if root.TagCount > 0 {
ret = t.firstTagForNode(1)
found = true
}
if address.Length == 0 {
// caller just looking for root tags
return found, ret, nil
}
var nodeIndex uint
if !address.IsLeftBitSet() {
nodeIndex = root.Left
} else {
nodeIndex = root.Right
}
// traverse the tree
for {
if nodeIndex == 0 {
return found, ret, nil
}
node := &t.nodes[nodeIndex]
matchCount := node.MatchCount(address)
if matchCount < node.prefixLength {
// didn't match the entire node - we're done
return found, ret, nil
}
// matched the full node - get its tags, then chop off the bits we've already matched and continue
if node.TagCount > 0 {
ret = t.firstTagForNode(nodeIndex)
found = true
}
if matchCount == address.Length {
// exact match - we're done
return found, ret, nil
}
// there's still more address - keep traversing
address.ShiftLeft(matchCount)
if !address.IsLeftBitSet() {
nodeIndex = node.Left
} else {
nodeIndex = node.Right
}
}
}
func (t *TreeV4) countNodes(nodeIndex uint) int {
nodeCount := 1
node := &t.nodes[nodeIndex]
if node.Left != 0 {
nodeCount += t.countNodes(node.Left)
}
if node.Right != 0 {
nodeCount += t.countNodes(node.Right)
}
return nodeCount
}
func (t *TreeV4) countTags(nodeIndex uint) int {
node := &t.nodes[nodeIndex]
tagCount := node.TagCount
if node.Left != 0 {
tagCount += t.countTags(node.Left)
}
if node.Right != 0 {
tagCount += t.countTags(node.Right)
}
return tagCount
}