-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathprotoTree.cpp
executable file
·1738 lines (1650 loc) · 57.4 KB
/
protoTree.cpp
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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*********************************************************************
*
* AUTHORIZATION TO USE AND DISTRIBUTE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that:
*
* (1) source code distributions retain this paragraph in its entirety,
*
* (2) distributions including binary code include this paragraph in
* its entirety in the documentation or other materials provided
* with the distribution, and
*
* (3) all advertising materials mentioning features or use of this
* software display the following acknowledgment:
*
* "This product includes software written and developed
* by Brian Adamson of the Naval Research Laboratory (NRL)."
*
* The name of NRL, the name(s) of NRL employee(s), or any entity
* of the United States Government may not be used to endorse or
* promote products derived from this software, nor does the
* inclusion of the NRL written and developed software directly or
* indirectly suggest NRL or United States Government endorsement
* of this product.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
********************************************************************/
/**
* @file protoTree.cpp
*
* @brief This is a general purpose prefix-based C++ Patricia tree.
* The code also provides an ability to iterate over items with a
* common prefix of arbitrary bit length
*/
#include "protoTree.h"
#include "protoDebug.h" // for PLOG()
#include <string.h>
#include <stdlib.h> // for labs()
ProtoTree::Item::Item()
: bit(0), parent((Item*)NULL), left((Item*)NULL), right((Item*)NULL)
{
}
ProtoTree::Item::~Item()
{
}
unsigned int ProtoTree::Item::GetDepth() const
{
unsigned int depth = 0;
const Item* p = this;
while (NULL != (p = p->parent)) depth++;
return depth;
} // end ProtoTree::Item::GetDepth()
ProtoTree::ItemPool::ItemPool()
: head(NULL)
{
}
ProtoTree::ItemPool::~ItemPool()
{
Destroy();
}
void ProtoTree::ItemPool::Destroy()
{
Item* item;
while ((item = Get())) delete item;
} // end ProtoTree::ItemPool::Destroy()
ProtoTree::Item* ProtoTree::ItemPool::Get()
{
Item* item = head;
if (NULL != item) head = item->GetPoolNext();
return item;
} // end ProtoTree::ItemPool::Get()
void ProtoTree::ItemPool::Put(Item& item)
{
item.SetPoolNext(head);
head = &item;
} // end ProtoTree::ItemPool::Put()
ProtoTree::ProtoTree()
: root((Item*)NULL)
{
}
ProtoTree::~ProtoTree()
{
}
void ProtoTree::Empty()
{
root = (ProtoTree::Item*)NULL;
UpdateIterators(NULL, Iterator::EMPTY);
} // end ProtoTree::Empty()
void ProtoTree::Destroy()
{
while (NULL != root)
{
Item* item = root;
Remove(*item);
delete item;
}
} // end ProtoTree::Destroy()
bool ProtoTree::PrefixIsEqual(const char* key,
unsigned int keysize,
const char* prefix,
unsigned int prefixSize,
Endian keyEndian)
{
if (prefixSize > keysize) return false;
unsigned int fullByteCount = (prefixSize >> 3);
unsigned int remBitCount = prefixSize & 0x07;
if (ENDIAN_BIG == keyEndian)
{
// Compare any "remainder bits" of the "prefix" to the
// corresponding bits of the "key"
// (we do this first to possibly avoid call to "memcmp()" below)
if (0 != remBitCount)
{
char remBitMask = (unsigned char)0xff << (8 - remBitCount);
// "remainder bits" are in last byte of big endian "prefix"
if ((key[fullByteCount] & remBitMask) != (prefix[fullByteCount] & remBitMask))
return false;
}
}
else
{
// Adjust "key" ptr to point at its prefix portion
key += (keysize >> 3);
if (0 != (keysize &0x07)) key++;
key -= fullByteCount;
// Compare any "remainder bits" of the "prefix" to the
// corresponding bits of the "key"
// (we do this first to possibly avoid call to "memcmp()" below)
if (0 != remBitCount)
{
char remBitMask = 0xff << (8 - remBitCount);
// "remainder bits" are in first byte of little endian "prefix"
if ((key[0] & remBitMask) != (prefix[0] & remBitMask))
return false;
// Compare any full byte portion of the key / prefix
if (0 != fullByteCount)
return (0 == memcmp(key+1, prefix+1, fullByteCount));
else
return true;
}
}
// Compare any full byte portion of the "prefix"
// to the corresponding "key" bytes
if (0 != fullByteCount)
return (0 == memcmp(key, prefix, fullByteCount));
else
return true;
} // end ProtoTree::PrefixIsEqual()
bool ProtoTree::KeysAreEqual(const char* key1,
const char* key2,
unsigned int keysize,
Endian keyEndian)
{
unsigned int fullByteCount = keysize >> 3;
unsigned int remBitCount = keysize & 0x07;
if (0 != remBitCount)
{
// Compare any "remainder bits" of the keys
// (we do this first to possibly avoid call to "memcmp()" below)
char remBitMask = 0xff << (8 - remBitCount);
if (ENDIAN_BIG == keyEndian)
{
// "remainder bits" are in last byte of big endian keys
if ((key1[fullByteCount] & remBitMask) != (key2[fullByteCount] & remBitMask))
return false;
}
else
{
// "remainder bits" are in first byte of little endian keys
if ((key1[0] & remBitMask) != (key2[0] & remBitMask))
return false;
// Compare any full byte portion of the keys
if (0 != fullByteCount)
return (0 == memcmp(key1+1, key2+1, fullByteCount));
else
return true;
}
}
// Compare any full bytes of the keys
if (0 != fullByteCount)
return (0 == memcmp(key1, key2, fullByteCount));
else
return true;
} // end ProtoTree::KeysAreEqual()
bool ProtoTree::ItemsAreEqual(const Item& item1, const Item& item2)
{
unsigned int keysize = item1.GetKeysize();
if (item2.GetKeysize() != keysize) return false;
Endian keyEndian = item1.GetEndian();
if (keyEndian != item2.GetEndian())
{
PLOG(PL_WARN, "ProtoTree::ItemsAreEqual() mis-matched key endian?!\n");
ASSERT(0);
return false;
}
return KeysAreEqual(item1.GetKey(), item2.GetKey(), keysize, keyEndian);
} // end ProtoTree::ItemsAreEqual()
bool ProtoTree::ItemIsEqual(const Item& item, const char* key, unsigned int keysize)
{
if (item.GetKeysize() != keysize) return false;
return KeysAreEqual(item.GetKey(), key, keysize, item.GetEndian());
} // end ProtoTree::ItemIsEqual()
bool ProtoTree::Bit(const char* key, unsigned int keysize, unsigned int index, Endian keyEndian)
{
if (index < keysize)
{
unsigned int byteIndex = index >> 3;
byteIndex = (ENDIAN_BIG == keyEndian) ? byteIndex : ((keysize - 1) >> 3) - byteIndex;
return (0 != (key[byteIndex] & (0x80 >> (index & 0x07))));
}
else if (index < (keysize + (sizeof(keysize) << 3)))
{
index -= keysize;
return (0 != (((char*)&keysize)[index >> 3] & (0x80 >> (index & 0x07))));
}
else
{
return false;
}
} // end ProtoTree::Bit()
ProtoTree::Item* ProtoTree::GetFirstItem() const
{
if (NULL != root)
{
if (root->left == root->right)
{
// 2-A) Only one node in this tree
return root;
}
else
{
// 2-B) Return left most node in this tree
Item* x = (root->left == root) ? root->right : root;
while (x->left->parent == x) x = x->left;
return (x->left);
}
}
return NULL;
} // end ProtoTree::GetFirstItem()
ProtoTree::Item* ProtoTree::GetLastItem() const
{
if (NULL != root)
{
// 2) Follow root or left of root all the way to right to find
// the last item (lexically) in the tree
Item* x = (root->right == root) ? root->left : root;
Item* p;
do
{
p = x;
x = x->right;
} while (p == x->parent);
return x;
}
return NULL;
} // end ProtoTree::GetLastItem()
bool ProtoTree::Insert(ProtoTree::Item& item)
{
if (NULL != root)
{
// 1) Find closest match to "item"
const char* key = item.GetKey();
unsigned int keysize = item.GetKeysize();
Endian keyEndian = item.GetEndian();
Item* x = root;
Item* p;
do
{
p = x;
x = Bit(key, keysize, x->bit, keyEndian) ? x->right : x->left;
} while (p == x->parent);
// 2) Then, find index of first differing bit ("dBit")
// (also look out for exact match!)
unsigned int dBit = 0;
// A) Do byte-wise comparison to extent possible
unsigned int keysizeMin, indexMax;
if (keysize < x->GetKeysize())
{
keysizeMin = keysize;
indexMax = x->GetKeysize() + (sizeof(unsigned int) << 3);
}
else
{
keysizeMin = x->GetKeysize();
indexMax = keysize + (sizeof(unsigned int) << 3);
}
const char* ptr1 = key;
const char* ptr2 = x->GetKey();
ASSERT(x->GetEndian() == keyEndian);
if (ENDIAN_LITTLE == keyEndian)
{
ptr1 += ((keysize - 1) >> 3);
ptr2 += ((x->GetKeysize() - 1) >> 3);
}
unsigned int fullByteBits = keysizeMin & ~0x07;
while (dBit < fullByteBits)
{
if (*ptr1 != *ptr2)
{
// B) Do bit-wise comparison on differing byte
unsigned char delta = *ptr1 ^ *ptr2;
ASSERT(0 != delta);
while (delta < 0x80)
{
delta <<= 1;
dBit++;
}
break;
}
if (ENDIAN_BIG == keyEndian)
{
ptr1++;
ptr2++;
}
else
{
ptr1--;
ptr2--;
}
dBit += 8;
}
ASSERT(dBit <= fullByteBits);
if (dBit == fullByteBits)
{
// C) Compare any remainder bit-by-bit
for (; dBit < indexMax; dBit++)
{
if (Bit(key, keysize, dBit, keyEndian) != Bit(x->GetKey(), x->GetKeysize(), dBit, keyEndian))
break;
}
if (dBit == indexMax)
{
PLOG(PL_WARN, "ProtoTree::Insert() Equivalent item already in tree!\n");
//ASSERT(0);
return false;
}
}
item.bit = dBit;
// 3) Find "item" insertion point
x = root;
do
{
p = x;
x = Bit(key, keysize, x->bit, keyEndian) ? x->right : x->left;
} while ((x->bit < dBit) && (p == x->parent));
// 4) Insert "item" into tree
if (Bit(key, keysize, dBit, keyEndian))
{
ASSERT(NULL != x);
item.left = x;
item.right = &item;
}
else
{
item.left = &item;
item.right = x;
}
item.parent = p;
if (Bit(key, keysize, p->bit, keyEndian))
p->right = &item;
else
p->left = &item;
if (p == x->parent)
x->parent = &item;
}
else
{
// tree is empty, so make "item" the tree root
root = &item;
item.parent = (Item*)NULL;
item.left = item.right = &item;
item.bit = 0;
}
// Note for ProtoTree, we call UpdateIterators() _after_
// insertion/removal since we just reset the iterators
UpdateIterators(&item, Iterator::INSERT);
return true;
} // end ProtoTree::Insert()
// Find node with backpointer to "item"
ProtoTree::Item* ProtoTree::FindPredecessor(ProtoTree::Item& item) const
{
// Find terminal "q" with backpointer to "item"
Item* x = &item;
Item* q;
const char* key = item.GetKey();
unsigned int keysize = item.GetKeysize();
Endian keyEndian = item.GetEndian();
do
{
q = x;
if (Bit(key, keysize, x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != &item);
return q;
} // end ProtoTree::FindPredecessor()
void ProtoTree::Remove(ProtoTree::Item& item)
{
ASSERT(0 != item.GetKeysize());
if (((&item == item.left) || (&item == item.right)) && (NULL != item.parent))
{
// non-root "item" that has at least one self-pointer
// (a.k.a an "external entry"?)
Item* orphan = (&item == item.left) ? item.right : item.left;
if (item.parent->left == &item)
item.parent->left = orphan;
else
item.parent->right = orphan;
if (orphan->bit > item.parent->bit)
orphan->parent = item.parent;
}
else
{
// Root or "item" with no self-pointers
// (a.k.a an "internal entry"?)
// 1) Find terminal "q" with backpointer to "item"
const char* key = item.GetKey();
unsigned int keysize = item.GetKeysize();
Endian keyEndian = item.GetEndian();
Item* x = &item;
Item* q;
do
{
q = x;
if (Bit(key, keysize, x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != &item);
if (NULL != q->parent)
{
// Non-root "q", so "q" is moved into the place of "item"
Item* s = NULL;
if (NULL == item.parent)
{
// There are always two nodes backpointing to "root"
// (unless root is the only node in the tree)
// "s" is the other of these besides "q"
// (We need to find "s" before we mess with the tree)
x = Bit(key, keysize, item.bit, keyEndian) ? item.left : item.right;
do
{
s = x;
if (Bit(key, keysize, x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != &item);
}
// A) Set bit index of "q" to that of "item"
q->bit = item.bit;
// B) Fix the parent, left, and right node pointers to "q"
// (removes "q" from its current place in the tree)
Item* parent = q->parent;
Item* child = (q->left == &item) ? q->right : q->left;
ASSERT(NULL != child);
if (parent->left == q)
parent->left = child;
else
parent->right = child;
if (child->bit > parent->bit)
child->parent = parent;
// C) Fix the item's left->parent and right->parent node pointers to "item"
// (places "q" into the current place of the "item" in the tree)
ASSERT(q != NULL);
if (item.left->parent == &item)
item.left->parent = q;
if (item.right->parent == &item)
item.right->parent = q;
if (NULL != item.parent)
{
if (item.parent->left == &item)
item.parent->left = q;
else
item.parent->right = q;
}
else
{
// "item" was root node, so update the "s" node
// backpointer to "q" instead of "item"
ASSERT(s != NULL);
ASSERT(s != &item);
if (s->left == &item)
s->left = q;
else
s->right = q;
root = q;
}
// E) Finally, "q" gets the pointers of the "item" being removed
// (which now _may_ include a pointer to itself)
if (NULL != item.parent)
ASSERT((&item != item.left) && (&item != item.right));
q->parent = item.parent;
q->left = (item.left == &item) ? q : item.left;
q->right = (item.right == &item) ? q : item.right;
}
else
{
// "root" is removed with none or one item left
ASSERT(q == &item);
Item* orphan = (q == q->left) ? q->right : q->left;
if (q == orphan)
{
root = (Item*)NULL;
}
else
{
root = orphan;
orphan->parent = NULL;
if (orphan->left == q)
orphan->left = orphan;
else
orphan->right = orphan;
orphan->bit = 0;
}
}
}
item.parent = item.left = item.right = (Item*)NULL;
UpdateIterators(&item, Iterator::REMOVE);
} // end ProtoTree::Remove()
ProtoTree::Item* ProtoTree::RemoveRoot()
{
Item* item = root;
if (NULL != item) Remove(*item);
return item;
} // end ProtoTree::RemoveRoot()
/**
* Find item with exact match to key and keysize
*/
ProtoTree::Item* ProtoTree::Find(const char* key,
unsigned int keysize) const
{
Item* x = root;
if (NULL != x)
{
Endian keyEndian = x->GetEndian();
Item* p;
do
{
p = x;
x = Bit(key, keysize, x->bit, keyEndian) ? x->right : x->left;
} while (x->parent == p);
return (ItemIsEqual(*x, key, keysize) ? x : NULL);
}
else
{
return (Item*)NULL;
}
} // end ProtoTree::Find()
/**
* Find item with "closest" match to key and keysize (biggest prefix match?)
*/
ProtoTree::Item* ProtoTree::FindClosestMatch(const char* key,
unsigned int keysize) const
{
Item* x = root;
if (NULL != x)
{
Endian keyEndian = x->GetEndian();
Item* p;
do
{
p = x;
x = Bit(key, keysize, x->bit, keyEndian) ? x->right : x->left;
} while ((x->parent == p) && (x->bit < keysize));
return x;
}
else
{
return (Item*)NULL;
}
} // end ProtoTree::FindClosestMatch()
/**
* Finds longest matching entry that is a prefix to "key"
*/
ProtoTree::Item* ProtoTree::FindPrefix(const char* key,
unsigned int keysize) const
{
// (TBD) Retest this code with new "size-agnostic" ProtoTree implementation
Item* x = root;
if (NULL != x)
{
Endian keyEndian = x->GetEndian();
Item* p;
do
{
p = x;
x = Bit(key, keysize, x->bit, keyEndian) ? x->right : x->left;
} while ((x->parent == p) && (x->bit < keysize));
if (PrefixIsEqual(key, keysize, x->GetKey(), x->GetKeysize(), keyEndian))
return x;
}
return NULL;
} // end ProtoTree::FindPrefix()
/**
* This finds prefix subtree root, (TBD) add find prefix
* subtree min, and find prefix subtree max methods
* (e.g. for "min", first find subtree root, and roll left ???)
*/
ProtoTree::Item* ProtoTree::FindPrefixSubtree(const char* prefix,
unsigned int prefixSize) const
{
// (TBD) Retest this code more with new "size-agnostic" ProtoTree implementation
Item* x = root;
if (NULL != x)
{
Endian keyEndian = x->GetEndian();
Item* p;
do
{
p = x;
x = Bit(prefix, prefixSize, x->bit, keyEndian) ? x->right : x->left;
} while ((x->parent == p) && (x->bit < prefixSize));
if (PrefixIsEqual(x->GetKey(), x->GetKeysize(), prefix, prefixSize, keyEndian))
return x;
}
return (Item*)NULL;
} // end ProtoTree::FindPrefixSubtree()
ProtoTree::Iterator::Iterator(ProtoTree& theTree, bool reverse, ProtoTree::Item* cursor)
: ProtoIterable::Iterator(theTree), prefix_size(0), prefix_item(NULL)
{
if (NULL != cursor)
{
reversed = reverse;
SetCursor(*cursor);
}
else
{
Reset(reverse); // Reset() sets all to defaults
}
}
ProtoTree::Iterator::~Iterator()
{
}
void ProtoTree::Iterator::Reset(bool reverse,
const char* prefix,
unsigned int prefixSize)
{
ProtoTree* tree = static_cast<ProtoTree*>(iterable);
prefix_size = 0;
prefix_item = prev = next = curr_hop = (Item*)NULL;
if ((NULL == tree) || (NULL == tree->root)) return;
if (0 != prefixSize)
{
if (NULL == prefix) return;
// Find root of subtree with matching prefix
// (TBD - there's a better way to find the min/max prefix matches via prefix00000 or prefix11111
ProtoTree::Item* prefixItem = tree->FindPrefixSubtree(prefix, prefixSize);
if (NULL == prefixItem) return;
// Temporarily "Reset()" the iterator and "SetCursor()" to find
reversed = reverse ? false : true;
SetCursor(*prefixItem);
Endian keyEndian = prefixItem->GetEndian();
if (reverse)
{
// Find the maximum value with matching prefix.
ProtoTree::Item* lastItem;
while (NULL != (lastItem = GetNextItem()))
{
if (!tree->PrefixIsEqual(lastItem->GetKey(), lastItem->GetKeysize(), prefix, prefixSize, keyEndian))
break; // The "cursor" is set to after the last matching item
}
if (NULL == lastItem) Reset(reverse);
}
else
{
// Find the minimum value with matching prefix.
ProtoTree::Item* firstItem;
while (NULL != (firstItem = GetPrevItem()))
{
if (!tree->PrefixIsEqual(firstItem->GetKey(), firstItem->GetKeysize(), prefix, prefixSize, keyEndian))
break; // The "cursor" is set to before the first matching item
}
if (NULL == firstItem) Reset(reverse);
}
prefix_size = prefixSize;
prefix_item = prefixItem;
return;
}
if (reverse)
{
// This code is basically the same as ProtoTree::GetLastItem()
if (NULL != tree->root)
{
// Follow left of root all the way to right to find
// the very last item (lexically) in the tree
Item* x = (tree->root->right == tree->root) ? tree->root->left : tree->root;
Item* p;
do
{
p = x;
x = x->right;
} while (p == x->parent);
prev = x;
}
reversed = true;
}
else
{
// This code is basically the same as ProtoTree::GetFirstItem()
// (although the code to find the "curr_hop" for iteration is different)
if (NULL != tree->root)
{
if (tree->root->left == tree->root->right)
{
// Only one entry in the tree
next = tree->root;
curr_hop = NULL;
}
else
{
// If root has a left side, go as far left as possible
// to find the very first item (lexically) in the tree
Item* x = (tree->root->left == tree->root) ? tree->root->right : tree->root;
while (x->left->parent == x) x = x->left;
next = x->left;
if (x->right->parent == x)
{
// Branch right and go as far left as possible
x = x->right;
while (x->left->parent == x) x = x->left;
}
curr_hop = x;
}
}
reversed = false;
}
} // end ProtoTree::Iterator::Reset()
void ProtoTree::Iterator::SetCursor(ProtoTree::Item& item)
{
ProtoTree* tree = static_cast<ProtoTree*>(iterable);
// Save prefix subtree info
unsigned int prefixSize = prefix_size;
ProtoTree::Item* prefixItem = prefix_item;
prefix_size = 0;
prefix_item = NULL;
if ((NULL== tree) || (NULL == tree->root))
{
prev = next = curr_hop = NULL;
}
else if (tree->root->left == tree->root->right)
{
ASSERT(&item == tree->root);
curr_hop = NULL;
if (reversed)
{
prev = NULL;
next = tree->root;
}
else
{
prev = tree->root;
next = NULL;
}
}
else if (reversed)
{
// Setting "cursor" for "reversed" iteration is easy.
curr_hop = NULL;
prev = &item;
GetPrevItem(); // note this sets "next"
}
else
{
// Setting "cursor" for forward iteration is a little more complicated.
// Given an "item", we can find the "curr_hop" for the tree
// entry that lexically precedes the "item"
// (We do a reverse iteration to find that preceding entry)
reversed = true;
prev = &item;
GetPrevItem(); // note "GetPrevItem()" also sets "next" as needed
if (NULL == GetPrevItem())
{
Reset(false);
// Move forward one place so "cursor" is correct position
GetNextItem();
}
else
{
// This finds the proper "curr_hop" that goes with
// the entry previous of "item" ...
if ((&item != tree->root) || (item.right != &item))
{
// Find the node's "predecessor"
// (has backpointer to "item"
curr_hop = tree->FindPredecessor(item);
}
else
{
// Instead, use the other node with backpointer to root "item"
ASSERT(&item == tree->root);
const char* key = item.GetKey();
unsigned int keysize = item.GetKeysize();
Endian keyEndian = item.GetEndian();
Item* s;
Item* x = tree->Bit(key, keysize, item.bit, keyEndian) ? item.left : item.right;
ASSERT((x == item.left) || (x == item.right));
do
{
s = x;
if (tree->Bit(key, keysize, x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != &item);
curr_hop = s;
}
// Move forward two places so "cursor" is correct position
reversed = false;
GetNextItem();
GetNextItem();
}
}
// Restore prefix subtree info
if (0 != prefixSize)
{
prefix_item = prefixItem;
prefix_size = prefixSize;
}
} // end ProtoTree::Iterator::SetCursor()
ProtoTree::Item* ProtoTree::Iterator::GetPrevItem()
{
if (NULL != prev)
{
ProtoTree* tree = static_cast<ProtoTree*>(iterable);
if (!reversed)
{
// This iterator has been moving forward
// so we need to turn it around.
reversed = true;
// temporarily suspend prefix matching (if applicable) to allow turn-around
unsigned savePrefixSize = prefix_size;
prefix_size = 0;
GetPrevItem();
prefix_size = savePrefixSize;
if (NULL == prev) return NULL;
}
Item* item = prev;
Endian keyEndian = item->GetEndian();
if (0 != prefix_size)
{
// Test "item" against our reference "prefix_item"
if ((NULL == prefix_item) ||
!tree->PrefixIsEqual(item->GetKey(), item->GetKeysize(), prefix_item->GetKey(), prefix_size, keyEndian))
{
prev = NULL;
return NULL;
}
}
Item* x;
// Find node "q" with backpointer to "item"
if ((NULL == item->parent) && (item->right == item))
x = item->left;
else
x = item;
Item* q;
do
{
q = x;
if (tree->Bit(item->GetKey(), item->GetKeysize(), x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != prev);
if (q->right != item)
{
// Go up the tree
do
{
x = q;
q = q->parent;
} while ((NULL != q) && (x == q->left));
if ((NULL == q) || (NULL == q->parent))
{
if ((NULL == q) || (q->left == q))
{
// We've bubbled completely up or
// root has no left side, so we're done
prev = NULL;
}
else
{
// We've iterated to root from the right side
// and root has a left side we should check out
// So, find the left-side predecessor to root "q"
Item* r = q;
x = q->left;
do
{
q = x;
if (tree->Bit(r->GetKey(), r->GetKeysize(), x->bit, keyEndian))
x = x->right;
else
x = x->left;
} while (x != r);
if (q->left != q)
{
// Go as far right of "q->left" as possible
q = q->left;
do
{
x = q;
q = q->right;
} while (x == q->parent);
}
prev = q;
}
next = item;
return item;
}
} // end if (q->right != prev)
if (q->left->parent != q)
{
if ((NULL == q->left->parent) &&
(q->left->left != q->left) &&
tree->Bit(q->GetKey(), q->GetKeysize(), 0, keyEndian))
{
// We've come from the right and there is a left of root
// So, go as far right of the left of root "q->left" as possible
x = q->left->left;
do
{
q = x;
x = x->right;
} while (q == x->parent);
prev = x;
}
else
{
// Otherwise, this is the appropriate iterate
prev = q->left;
}
}
else
{
// Go as far right of "q->left" as possible
x = q->left;
do
{
q = x;