-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimpl.go
More file actions
740 lines (685 loc) · 16.3 KB
/
impl.go
File metadata and controls
740 lines (685 loc) · 16.3 KB
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
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
// Copyright © 2025 Prabhjot Singh Sethi, All Rights reserved
// Author: Prabhjot Singh Sethi <prabhjot.sethi@gmail.com>
//
// Initial logic was contributed by Prabhjot Singh Sethi in
// 2013 to Contail Systems (Juniper Networks) as part of the
// Linux Foundation open source project Tungsten Fabric, while
// originally it was developed for networks centric usecases
// using C++ as the programming language
//
// This repo repurpose the core logic and is rewritten in golang
// for different extensions and use cases.
// Over the time it is expected to significantly diverge from the
// original implementation, but the core logic remains the same.
// Original source:
// https://github.com/tungstenfabric/tf-common/blob/master/base/patricia.h
package patricia
// Key is an interface that must be implemented by any key type used in the Patricia tree.
// It provides methods to get the bit length of the key and to retrieve a byte at a given position.
type Key interface {
// BitLength returns the number of bits in the key.
BitLength() int
// ByteValue returns the byte value at the specified position in the key.
ByteValue(int) byte
}
// node represents a node in the Patricia tree.
// Each node may be an internal node (used for branching) or a leaf node (storing actual data).
type node[K Key, D any] struct {
left *node[K, D] // Left child node
right *node[K, D] // Right child node
intnode bool // True if this is an internal node, false if it is a leaf
bitpos int // Bit position used for branching at this node
key *K // Pointer to the key (only set for leaf nodes)
data *D // Pointer to the data (only set for leaf nodes)
}
// BitLength returns the bit length of the key stored in this node.
// If the key is nil, it returns 0.
func (n *node[K, D]) BitLength() int {
if n.key == nil {
return 0
}
return (*n.key).BitLength()
}
// ByteValue returns the byte at the given position in the key stored in this node.
// If the key is nil, it returns 0.
func (n *node[K, D]) ByteValue(pos int) byte {
if n.key == nil {
return 0
}
return (*n.key).ByteValue(pos)
}
// treeImpl represents a Patricia tree (Practical Algorithm to Retrieve Information Coded in Alphanumeric).
// It is a space-optimized trie data structure where each node with only one child is merged with its child.
// The Patricia tree supports efficient insert, remove, and search operations for variable-length keys.
type treeImpl[K Key, D any] struct {
nodes int // Number of leaf nodes (actual data entries)
intNodes int // Number of internal nodes (used for branching)
root *node[K, D] // Pointer to the root node of the tree
}
// createNew creates a new node of type node[K, D].
// This is a simple allocation function that returns a zero-initialized node.
func createNew[K Key, D any]() *node[K, D] {
return &node[K, D]{}
}
// getBit returns the value of the bit at position pos in the given node's key.
// Returns false if the node is nil or the position is out of bounds.
func (t *treeImpl[K, D]) getBit(node *node[K, D], pos int) bool {
if node == nil {
return false
}
if pos < 0 || pos >= node.BitLength() {
return false
}
return (node.ByteValue(pos>>3) & (0x80 >> (pos & 7))) != 0
}
// compareNodes compares two nodes for key equality.
// Returns true if the keys are equal in both length and content.
func (t *treeImpl[K, D]) compareNodes(n_left, n_right *node[K, D]) bool {
if n_left == nil || n_right == nil {
return false
}
if n_left.BitLength() != n_right.BitLength() {
return false
}
bitLength := n_left.BitLength()
// Compare byte by byte for the full bytes.
byteLen := bitLength >> 3
pos := 0
for ; pos < byteLen; pos++ {
if n_left.ByteValue(pos) != n_right.ByteValue(pos) {
return false
}
}
// Compare remaining bits if any.
for pos <<= 3; pos < bitLength; pos++ {
if t.getBit(n_left, pos) != t.getBit(n_right, pos) {
return false
}
}
return true
}
// compare compares two nodes' keys starting from a given bit position.
// Returns the position of the first differing bit and whether the keys are equal up to the shortest length.
func (t *treeImpl[K, D]) compare(node_left, node_right *node[K, D], start int) (pos int, isEqual bool) {
isEqual = false
if node_left == nil || node_right == nil {
return
}
shortLen := 0
if node_left.BitLength() < node_right.BitLength() {
shortLen = node_left.BitLength()
isEqual = false
} else {
shortLen = node_right.BitLength()
isEqual = (node_left.BitLength() == node_right.BitLength())
}
byteLen := shortLen >> 3
// Compare bytes first.
for pos = start >> 3; pos < byteLen; pos++ {
if node_left.ByteValue(pos) != node_right.ByteValue(pos) {
break
}
}
pos <<= 3
if pos < start {
pos = start
}
// Compare remaining bits.
for ; pos < shortLen; pos++ {
if t.getBit(node_left, pos) != t.getBit(node_right, pos) {
isEqual = false
return
}
}
return
}
// rewireRightMost rewires the rightmost child of x to point to p.
// Used during node removal and tree restructuring.
func (t *treeImpl[K, D]) rewireRightMost(p *node[K, D], x *node[K, D]) *node[K, D] {
if x == nil {
return nil
}
for x.right != nil && x.right.bitpos > x.bitpos {
x = x.right
}
pRight := x.right
x.right = p
return pRight
}
// GetLastNode returns the last (rightmost) node in the tree.
// Deprecated: will be removed in future versions. Kept for backward compatibility.
func (t *treeImpl[K, D]) GetLastNode() *node[K, D] {
if t.root == nil {
return nil
}
x := t.root
for x != nil {
if x.right != nil {
if x.right.bitpos < x.bitpos {
if x.left == nil {
return x
}
x = x.left
} else {
x = x.right
}
} else {
if x.left == nil {
return x
}
x = x.left
}
}
return x
}
// GetPrevNode returns the previous node in the tree before node n.
// Deprecated: will be removed in future versions. Kept for backward compatibility.
func (t *treeImpl[K, D]) GetPrevNode(n *node[K, D]) *node[K, D] {
if n == nil || t.root == nil {
return nil
}
var l *node[K, D]
p := t.root
x := p
rightTurn := x
greatestPartial := x
for x != nil {
if x.bitpos > n.BitLength() {
x = nil
break
} else if x.bitpos == n.BitLength() && !x.intnode {
break
}
p = x
if t.getBit(n, x.bitpos) {
rightTurn = x
x = x.right
} else {
if !x.intnode {
greatestPartial = x
}
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
x = nil
break
}
}
if x == nil || !t.compareNodes(n, x) {
return nil
}
if rightTurn != nil && greatestPartial != nil {
if greatestPartial.bitpos > rightTurn.bitpos {
return greatestPartial
}
}
if rightTurn == nil {
return greatestPartial
}
x = rightTurn.left
for x != nil {
l = x.left
r := x.right
if r != nil && r.bitpos > x.bitpos {
x = r
} else if l != nil {
x = l
} else {
return x
}
}
return x
}
// getNextNode returns the next node in the tree after node n.
// If n is nil, it returns the leftmost node (the first node in order).
func (t *treeImpl[K, D]) getNextNode(n *node[K, D]) *node[K, D] {
if t.root == nil {
return nil
}
x := t.root
if n != nil || x.intnode {
if n != nil {
x = n
}
l := x
for x != nil {
if x.bitpos < l.bitpos {
l = x
x = l.right
} else {
l = x
if l.left != nil {
x = l.left
} else {
x = l.right
}
}
if x != nil && x.bitpos > l.bitpos && !x.intnode {
break
}
}
}
return x
}
// LPMFind performs a longest prefix match search for the given key.
// Returns the data pointer for the node with the longest matching prefix, or nil if no match is found.
// Logic: Traverses the tree, comparing bits of the search key with each node.
// If a node matches up to its bit position, it is a candidate for the longest prefix match.
func (t *treeImpl[K, D]) LPMFind(key *K) *D {
if t.root == nil {
return nil
}
n := createNew[K, D]()
n.key = key
var p, x, l *node[K, D]
x = t.root
i := 0
for x != nil {
if !x.intnode {
var ok bool
if i, ok = t.compare(n, x, i); ok {
return x.data
}
if i == x.bitpos {
l = x
}
}
if x.bitpos > n.BitLength() {
break
}
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
break
}
}
if l != nil {
return l.data
}
return nil
}
// FindNextNode is deprecated. Use getNextNode instead.
// Returns the next node in the tree after node n, or nil if there is none.
// Logic: Traverses the tree to find the next node in key order after n.
func (t *treeImpl[K, D]) FindNextNode(n *node[K, D]) *node[K, D] {
if n == nil || t.root == nil {
return nil
}
p := t.root
l := p
x := p
i := 0
for x != nil {
if !x.intnode {
var ok bool
if i, ok = t.compare(n, x, i); ok {
return t.getNextNode(x)
}
if x.bitpos > n.BitLength() || i != x.bitpos {
break
}
l = x
}
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
break
}
}
if l != nil {
x = l
for x != nil && x.bitpos <= i {
l = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && l.bitpos >= x.bitpos {
break
}
}
if n.BitLength() != l.bitpos {
if t.getBit(n, l.bitpos) {
if x == nil {
return nil
}
if l.bitpos > x.bitpos {
for x != nil && l.bitpos > x.bitpos {
l = x
x = x.right
}
l = x
} else if t.getBit(n, i) {
for x.right != nil && x.bitpos < x.right.bitpos {
x = x.right
}
l = x
x = x.right
for x != nil && l.bitpos > x.bitpos {
l = x
x = x.right
}
l = x
} else {
l = x
}
} else {
if x == nil || t.getBit(n, i) {
x = l.right
for x != nil && l.bitpos > x.bitpos {
l = x
x = x.right
}
l = x
} else {
l = x
}
}
if x != nil && !x.intnode {
return x
}
}
return t.getNextNode(l)
} else {
if !t.getBit(n, i) {
// all elements of the tree are on right
return x
}
}
return nil
}
// FindNode searches for a node with the exact key and returns its data pointer.
// Returns nil if the key is not found.
// Logic: Traverses the tree, following the bits of the search key, and compares the found node for exact match.
func (t *treeImpl[K, D]) FindNode(key *K) *D {
if t.root == nil {
return nil
}
n := createNew[K, D]()
n.key = key
p := t.root
x := p
for x != nil {
if x.bitpos > n.BitLength() {
x = nil
break
} else if x.bitpos == n.BitLength() && !x.intnode {
break
}
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
break
}
}
if x == nil || !t.compareNodes(n, x) {
return nil
}
return x.data
}
// Remove deletes the node with the given key from the tree.
// Returns true if the node was found and removed, false otherwise.
// Logic: Traverses the tree to find the node, then restructures the tree to maintain the Patricia property.
func (t *treeImpl[K, D]) Remove(key *K) bool {
if t.root == nil {
return false
}
n := createNew[K, D]()
n.key = key
var pPrev, p *node[K, D]
x := t.root
// Traverse the tree to find the node to remove.
for x != nil {
if x.bitpos > n.BitLength() {
x = nil
break
} else if x.bitpos == n.BitLength() && !x.intnode {
break
}
pPrev = p
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
/* no x to deal with */
x = nil
break
}
}
// If the node was not found or does not match, return false.
if x == nil || !t.compareNodes(n, x) {
return false
}
var a *node[K, D]
// Case 1: Node has both left and right children, and right child is a descendant.
if x.left != nil && x.right != nil && x.bitpos < x.right.bitpos {
// Replace the node with a new internal node.
a = createNew[K, D]()
a.bitpos = x.bitpos
a.intnode = true
t.intNodes++
a.left = x.left
a.right = x.right
t.rewireRightMost(a, x.left)
if p == nil {
t.root = a
} else if t.getBit(x, p.bitpos) {
p.right = a
} else {
p.left = a
}
// Case 2: Node has only a left child.
} else if x.left != nil {
if p == nil {
t.root = x.left
} else if t.getBit(x, p.bitpos) {
p.right = x.left
} else {
p.left = x.left
}
t.rewireRightMost(x.right, x.left)
// Case 3: Node has only a right child, and right child is a descendant.
} else if x.right != nil && x.bitpos < x.right.bitpos {
if p == nil {
t.root = x.right
} else if t.getBit(x, p.bitpos) {
p.right = x.right
} else {
p.left = x.right
}
// Case 4: Node is a leaf or has no children.
} else {
if p == nil {
t.root = nil
} else if p.intnode {
if t.getBit(x, p.bitpos) {
a = p.left
// RewireRightMost((pPrev.left == p) ? pPrev : nil, a)
t.rewireRightMost(x.right, a)
} else {
a = p.right
}
if pPrev == nil {
t.root = a
} else if t.getBit(x, pPrev.bitpos) {
pPrev.right = a
} else {
pPrev.left = a
}
// Clear pointers on the removed node to help GC release key/data and detached children sooner.
p.left = nil
p.right = nil
p.key = nil
p.data = nil
t.intNodes--
} else {
if t.getBit(x, p.bitpos) {
p.right = x.right
} else {
p.left = nil
}
}
}
// Clear pointers on the removed node to help GC release key/data and detached children sooner.
x.left = nil
x.right = nil
x.key = nil
x.data = nil
t.nodes--
return true
}
// Insert adds a new key/data pair to the tree.
// Returns false if the key already exists, true if the insertion was successful.
// Logic: Traverses the tree to find the correct insertion point, then inserts the new node and restructures as needed.
func (t *treeImpl[K, D]) Insert(key *K, data *D) bool {
n := createNew[K, D]()
n.key = key
n.data = data
x := t.root
var p *node[K, D]
// Traverse the tree to find the correct insertion point.
for x != nil {
if x.bitpos >= n.BitLength() && !x.intnode {
break
}
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
x = nil
break
}
}
i := 0
l := x
if x == nil {
l = p
}
if l != nil {
var ok bool
if i, ok = t.compare(n, l, 0); ok {
// Key already exists.
return false
}
if i != n.BitLength() || i != l.bitpos {
p = nil
x = t.root
for x != nil && x.bitpos <= i && x.bitpos < n.BitLength() {
p = x
if t.getBit(n, x.bitpos) {
x = x.right
} else {
x = x.left
}
if x != nil && p.bitpos >= x.bitpos {
x = nil
break
}
}
}
}
t.nodes++
n.left = nil
n.right = nil
n.bitpos = n.BitLength()
if x != nil {
if x.bitpos == i {
n.right = x.right
n.left = x.left
t.rewireRightMost(n, x.left)
// Clear pointers on the removed node to help GC release key/data and detached children sooner.
x.left = nil
x.right = nil
x.key = nil
x.data = nil
t.intNodes--
l = n
} else {
if i == n.BitLength() {
if t.getBit(l, i) {
n.right = x
} else {
n.left = x
n.right = t.rewireRightMost(n, x)
}
l = n
} else {
l = createNew[K, D]()
t.intNodes++
l.bitpos = i
l.intnode = true
if t.getBit(n, i) {
l.left = x
l.right = n
n.right = t.rewireRightMost(l, x)
} else {
l.left = n
l.right = x
n.right = l
}
}
}
} else {
if p != nil {
if t.getBit(n, p.bitpos) {
n.right = p.right
} else {
n.right = p
}
}
l = n
}
if p != nil {
if t.getBit(n, p.bitpos) {
p.right = l
} else {
p.left = l
}
} else {
t.root = l
}
return true
}
// All returns a function that iterates over all key/data pairs in the tree in order.
// The provided yield function is called for each key/data pair. If yield returns false, iteration stops.
// Logic: Uses getNextNode to traverse the tree in key order, yielding each leaf node's key and data.
func (t *treeImpl[K, D]) All() func(func(K, D) bool) {
return func(yield func(K, D) bool) {
if t.root == nil {
// If the tree is empty, nothing to yield.
return
}
// Start with the leftmost node (smallest key).
n := t.getNextNode(nil)
for n != nil {
// Only yield nodes that have both key and data set (i.e., leaf nodes).
if n.data != nil && n.key != nil {
if !yield(*n.key, *n.data) {
// If yield returns false, stop iteration early.
return
}
}
// Move to the next node in order.
n = t.getNextNode(n)
}
}
}