/
store.h
1482 lines (1231 loc) · 54.8 KB
/
store.h
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
/**
* Copyright (C) 2018-present MongoDB, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the Server Side Public License, version 1,
* as published by MongoDB, Inc.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* Server Side Public License for more details.
*
* You should have received a copy of the Server Side Public License
* along with this program. If not, see
* <http://www.mongodb.com/licensing/server-side-public-license>.
*
* As a special exception, the copyright holders give permission to link the
* code of portions of this program with the OpenSSL library under certain
* conditions as described in each individual source file and distribute
* linked combinations including the program with the OpenSSL library. You
* must comply with the Server Side Public License in all respects for
* all of the code used other than as permitted herein. If you modify file(s)
* with this exception, you may extend this exception to your version of the
* file(s), but you are not obligated to do so. If you do not wish to do so,
* delete this exception statement from your version. If you delete this
* exception statement from all source files in the program, then also delete
* it in the license file.
*/
#pragma once
#include <array>
#include <boost/optional.hpp>
#include <cstring>
#include <exception>
#include <iostream>
#include <memory>
#include <string.h>
#include <vector>
#include "mongo/util/assert_util.h"
namespace mongo {
namespace biggie {
class merge_conflict_exception : std::exception {
virtual const char* what() const noexcept {
return "conflicting changes prevent successful merge";
}
};
/**
* RadixStore is a Trie data structure with the ability to share nodes among copies of trees to
* minimize data duplication. Each node has a notion of ownership and if modifications are made to
* non-uniquely owned nodes, they are copied to prevent dirtying the data for the other owners of
* the node.
*/
template <class Key, class T>
class RadixStore {
class Node;
class Head;
friend class RadixStoreTest;
public:
using mapped_type = T;
using value_type = std::pair<const Key, mapped_type>;
using allocator_type = std::allocator<value_type>;
using pointer = typename std::allocator_traits<allocator_type>::pointer;
using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using uint8_t = std::uint8_t;
template <class pointer_type, class reference_type>
class radix_iterator {
friend class RadixStore;
public:
using iterator_category = std::forward_iterator_tag;
using value_type = typename RadixStore::value_type;
using difference_type = std::ptrdiff_t;
using pointer = pointer_type;
using reference = reference_type;
radix_iterator() : _root(nullptr), _current(nullptr) {}
~radix_iterator() {
updateTreeView(/*stopIfMultipleCursors=*/true);
}
radix_iterator& operator++() {
repositionIfChanged();
_findNext();
return *this;
}
radix_iterator operator++(int) {
repositionIfChanged();
radix_iterator old = *this;
++*this;
return old;
}
bool operator==(const radix_iterator& other) {
repositionIfChanged();
return _current == other._current;
}
bool operator!=(const radix_iterator& other) {
repositionIfChanged();
return _current != other._current;
}
reference operator*() {
repositionIfChanged();
return *(_current->_data);
}
const_pointer operator->() {
repositionIfChanged();
return &*(_current->_data);
}
/**
* Attempts to restore the iterator on its former position in the updated tree if the tree
* has changed.
*
* If the former position has been erased, the iterator finds the next node. It is
* possible that no next node is available, so at that point the cursor is exhausted and
* points to the end.
*/
void repositionIfChanged() {
if (!_current || !_root->_nextVersion)
return;
invariant(_current->_data);
// Copy the key from _current before we move our _root reference.
auto key = _current->_data->first;
updateTreeView();
RadixStore store(*_root);
// Find the same or next node in the updated tree.
_current = store.lower_bound(key)._current;
}
private:
radix_iterator(const std::shared_ptr<Head>& root) : _root(root), _current(nullptr) {}
radix_iterator(const std::shared_ptr<Head>& root, Node* current)
: _root(root), _current(current) {}
/**
* This function traverses the tree to find the next left-most node with data. Modifies
* '_current' to point to this node. It uses a pre-order traversal ('visit' the current
* node itself then 'visit' the child subtrees from left to right).
*/
void _findNext() {
// If 'current' is a nullptr there is no next node to go to.
if (_current == nullptr)
return;
// If 'current' is not a leaf, continue moving down and left in the tree until the next
// node.
if (!_current->isLeaf()) {
_traverseLeftSubtree();
return;
}
// Get path from root to '_current' since it is required to traverse up the tree.
Key key = _current->_data->first;
std::vector<Node*> context = RadixStore::_buildContext(key, _root.get());
// 'node' should equal '_current' because that should be the last element in the stack.
// Pop back once more to get access to its parent node. The parent node will enable
// traversal through the neighboring nodes, and if there are none, the iterator will
// move up the tree to continue searching for the next node with data.
Node* node = context.back();
context.pop_back();
// In case there is no next node, set _current to be 'nullptr' which will mark the end
// of the traversal.
_current = nullptr;
while (!context.empty()) {
uint8_t oldKey = node->_trieKey.front();
node = context.back();
context.pop_back();
// Check the children right of the node that the iterator was at already. This way,
// there will be no backtracking in the traversal.
for (auto iter = oldKey + 1 + node->_children.begin();
iter != node->_children.end();
++iter) {
// If the node has a child, then the sub-tree must have a node with data that
// has not yet been visited.
if (*iter != nullptr) {
// If the current node has data, return it and exit. If not, continue
// following the nodes to find the next one with data. It is necessary to go
// to the left-most node in this sub-tree.
if ((*iter)->_data) {
_current = iter->get();
return;
}
_current = iter->get();
_traverseLeftSubtree();
return;
}
}
}
return;
}
void _traverseLeftSubtree() {
// This function finds the next left-most node with data under the sub-tree where
// '_current' is root. However, it cannot return the root, and hence at least 1
// iteration of the while loop is required.
do {
for (auto child : _current->_children) {
if (child != nullptr) {
_current = child.get();
break;
}
}
} while (!_current->_data);
}
void updateTreeView(bool stopIfMultipleCursors = false) {
while (_root && _root->_nextVersion) {
if (stopIfMultipleCursors && _root.use_count() > 1)
return;
bool clearPreviousFlag = _root.use_count() == 1;
_root = _root->_nextVersion;
if (clearPreviousFlag)
_root->_hasPreviousVersion = false;
}
}
// "_root" is a pointer to the root of the tree over which this is iterating.
std::shared_ptr<Head> _root;
// "_current" is the node that the iterator is currently on. _current->_data will never be
// boost::none (unless it is within the process of tree traversal), and _current will be
// become a nullptr once there are no more nodes left to iterate.
Node* _current;
};
using iterator = radix_iterator<pointer, value_type&>;
using const_iterator = radix_iterator<const_pointer, const value_type&>;
template <class pointer_type, class reference_type>
class reverse_radix_iterator {
friend class RadixStore;
friend class radix_iterator<pointer_type, reference_type&>;
public:
using value_type = typename RadixStore::value_type;
using difference_type = std::ptrdiff_t;
using pointer = pointer_type;
using reference = reference_type;
reverse_radix_iterator() : _root(nullptr), _current(nullptr) {}
reverse_radix_iterator(const const_iterator& it) : _root(it._root), _current(it._current) {
// If the iterator passed in is at the end(), then set _current to root which is
// equivalent to rbegin(). Otherwise, move the iterator back one node, due to the fact
// that the relationship &*r == &*(i-1) must be maintained for any reverse iterator 'r'
// and forward iterator 'i'.
if (_current == nullptr) {
// If the tree is empty, then leave '_current' as nullptr.
if (_root->isLeaf())
return;
_current = _root.get();
_traverseRightSubtree();
} else {
_findNextReverse();
}
}
reverse_radix_iterator(const iterator& it) : _root(it._root), _current(it._current) {
if (_current == nullptr) {
_current = _root;
_traverseRightSubtree();
} else {
_findNextReverse();
}
}
~reverse_radix_iterator() {
updateTreeView(/*stopIfMultipleCursors=*/true);
}
reverse_radix_iterator& operator++() {
repositionIfChanged();
_findNextReverse();
return *this;
}
reverse_radix_iterator operator++(int) {
repositionIfChanged();
reverse_radix_iterator old = *this;
++*this;
return old;
}
bool operator==(const reverse_radix_iterator& other) {
repositionIfChanged();
return _current == other._current;
}
bool operator!=(const reverse_radix_iterator& other) {
repositionIfChanged();
return _current != other._current;
}
reference operator*() {
repositionIfChanged();
return *(_current->_data);
}
const_pointer operator->() {
repositionIfChanged();
return &*(_current->_data);
}
/**
* Attempts to restore the iterator on its former position in the updated tree if the tree
* has changed.
*
* If the former position has been erased, the iterator finds the next node. It is
* possible that no next node is available, so at that point the cursor is exhausted and
* points to the end.
*/
void repositionIfChanged() {
if (!_current || !_root->_nextVersion)
return;
invariant(_current->_data);
// Copy the key from _current before we move our _root reference.
auto key = _current->_data->first;
updateTreeView();
RadixStore store(*_root);
// Find the same or next node in the updated tree.
const_iterator it = store.lower_bound(key);
// Couldn't find any nodes with key greater than currentKey in lower_bound().
// So make _current point to the beginning, since rbegin() will point to the
// previous node before key.
if (!it._current)
_current = store.rbegin()._current;
else {
_current = it._current;
// lower_bound(), moved us one up in a forwards direction since the currentKey
// didn't exist anymore, move one back.
if (_current->_data->first > key)
_findNextReverse();
}
}
private:
reverse_radix_iterator(const std::shared_ptr<Head>& root)
: _root(root), _current(nullptr) {}
reverse_radix_iterator(const std::shared_ptr<Head>& root, Node* current)
: _root(root), _current(current) {}
void _findNextReverse() {
// Reverse find iterates through the tree to find the "next" node containing data,
// searching from right to left. Normally a pre-order traversal is used, but for
// reverse, the ordering is to visit child nodes from right to left, then 'visit'
// current node.
if (_current == nullptr)
return;
Key key = _current->_data->first;
std::vector<Node*> context = RadixStore::_buildContext(key, _root.get());
Node* node = context.back();
context.pop_back();
// Due to the nature of the traversal, it will always be necessary to move up the tree
// first because when the 'current' node was visited, it meant all its children had been
// visited as well.
uint8_t oldKey;
_current = nullptr;
while (!context.empty()) {
oldKey = node->_trieKey.front();
node = context.back();
context.pop_back();
// After moving up in the tree, continue searching for neighboring nodes to see if
// they have data, moving from right to left.
for (int i = oldKey - 1; i >= 0; i--) {
if (node->_children[i] != nullptr) {
// If there is a sub-tree found, it must have data, therefore it's necessary
// to traverse to the right most node.
_current = node->_children[i].get();
_traverseRightSubtree();
return;
}
}
// If there were no sub-trees that contained data, and the 'current' node has data,
// it can now finally be 'visited'.
if (node->_data) {
_current = node;
return;
}
}
}
void _traverseRightSubtree() {
// This function traverses the given tree to the right most leaf of the subtree where
// 'current' is the root.
do {
for (auto iter = _current->_children.rbegin(); iter != _current->_children.rend();
++iter) {
if (*iter != nullptr) {
_current = iter->get();
break;
}
}
} while (!_current->isLeaf());
}
void updateTreeView(bool stopIfMultipleCursors = false) {
while (_root && _root->_nextVersion) {
if (stopIfMultipleCursors && _root.use_count() > 1)
return;
bool clearPreviousFlag = _root.use_count() == 1;
_root = _root->_nextVersion;
if (clearPreviousFlag)
_root->_hasPreviousVersion = false;
}
}
// "_root" is a pointer to the root of the tree over which this is iterating.
std::shared_ptr<Head> _root;
// "_current" is a the node that the iterator is currently on. _current->_data will never be
// boost::none, and _current will be become a nullptr once there are no more nodes left to
// iterate.
Node* _current;
};
using reverse_iterator = reverse_radix_iterator<pointer, value_type&>;
using const_reverse_iterator = reverse_radix_iterator<const_pointer, const value_type&>;
// Constructors
RadixStore() : _root(std::make_shared<Head>()) {}
RadixStore(const RadixStore& other) : _root(std::make_shared<Head>(*(other._root))) {}
RadixStore(const Head& other) : _root(std::make_shared<Head>(other)) {}
friend void swap(RadixStore& first, RadixStore& second) {
std::swap(first._root, second._root);
}
RadixStore(RadixStore&& other) {
_root = std::move(other._root);
}
RadixStore& operator=(RadixStore other) {
swap(*this, other);
return *this;
}
// Equality
bool operator==(const RadixStore& other) const {
if (_root->_count != other._root->_count || _root->_dataSize != other._root->_dataSize)
return false;
RadixStore::const_iterator iter = this->begin();
RadixStore::const_iterator other_iter = other.begin();
while (iter != this->end()) {
if (other_iter == other.end() || *iter != *other_iter) {
return false;
}
iter++;
other_iter++;
}
return other_iter == other.end();
}
bool operator!=(const RadixStore& other) const {
return !(*this == other);
}
// Capacity
bool empty() const {
// Not relying on size() internally, as it may be updated late.
return _root->isLeaf() && !_root->_data;
}
size_type size() const {
return _root->_count;
}
size_type dataSize() const {
return _root->_dataSize;
}
bool hasBranch() const {
return _root->_nextVersion ? true : false;
}
// Modifiers
void clear() noexcept {
_root = std::make_shared<Head>();
}
std::pair<const_iterator, bool> insert(value_type&& value) {
Key key = value.first;
Node* node = _findNode(key);
if (node != nullptr || key.size() == 0)
return std::make_pair(end(), false);
return _upsertWithCopyOnSharedNodes(key, std::move(value));
}
std::pair<const_iterator, bool> update(value_type&& value) {
Key key = value.first;
// Ensure that the item to be updated exists.
auto item = RadixStore::find(key);
if (item == RadixStore::end())
return std::make_pair(item, false);
return _upsertWithCopyOnSharedNodes(key, std::move(value));
}
/**
* Returns whether the key was removed.
*/
bool erase(const Key& key) {
std::vector<std::pair<Node*, bool>> context;
Node* prev = _root.get();
int rootUseCount = _root->_hasPreviousVersion ? 2 : 1;
bool isUniquelyOwned = _root.use_count() == rootUseCount;
context.push_back(std::make_pair(prev, isUniquelyOwned));
Node* node = nullptr;
const uint8_t* charKey = reinterpret_cast<const uint8_t*>(key.data());
size_t depth = prev->_depth + prev->_trieKey.size();
while (depth < key.size()) {
uint8_t c = charKey[depth];
node = prev->_children[c].get();
if (node == nullptr) {
return false;
}
// If the prefixes mismatch, this key cannot exist in the tree.
size_t p = _comparePrefix(node->_trieKey, charKey + depth, key.size() - depth);
if (p != node->_trieKey.size()) {
return false;
}
isUniquelyOwned = isUniquelyOwned && prev->_children[c].use_count() == 1;
context.push_back(std::make_pair(node, isUniquelyOwned));
depth = node->_depth + node->_trieKey.size();
prev = node;
}
// Found the node, now remove it.
Node* deleted = context.back().first;
context.pop_back();
// If the to-be deleted node is an internal node without data it is hidden from the user and
// should not be deleted
if (!deleted->_data)
return false;
if (!deleted->isLeaf()) {
// The to-be deleted node is an internal node, and therefore updating its data to be
// boost::none will "delete" it.
_upsertWithCopyOnSharedNodes(key, boost::none);
return true;
}
Node* parent = context.at(0).first;
isUniquelyOwned = context.at(0).second;
if (!isUniquelyOwned) {
invariant(!_root->_nextVersion);
invariant(_root.use_count() > rootUseCount);
_root->_nextVersion = std::make_shared<Head>(*_root);
_root = _root->_nextVersion;
_root->_hasPreviousVersion = true;
parent = _root.get();
}
size_t sizeOfRemovedData = node->_data->second.size();
_root->_dataSize -= sizeOfRemovedData;
_root->_count--;
for (size_t depth = 1; depth < context.size(); depth++) {
Node* child = context.at(depth).first;
isUniquelyOwned = context.at(depth).second;
uint8_t childFirstChar = child->_trieKey.front();
if (!isUniquelyOwned) {
parent->_children[childFirstChar] = std::make_shared<Node>(*child);
child = parent->_children[childFirstChar].get();
}
parent = child;
}
// Handle the deleted node, as it is a leaf.
parent->_children[deleted->_trieKey.front()] = nullptr;
// 'parent' may only have one child, in which case we need to evaluate whether or not
// this node is redundant.
_compressOnlyChild(parent);
return true;
}
void merge3(const RadixStore& base, const RadixStore& other) {
std::vector<Node*> context;
std::vector<uint8_t> trieKeyIndex;
difference_type deltaCount = _root->_count - base._root->_count;
difference_type deltaDataSize = _root->_dataSize - base._root->_dataSize;
invariant(this->_root->_trieKey.size() == 0 && base._root->_trieKey.size() == 0 &&
other._root->_trieKey.size() == 0);
_merge3Helper(
this->_root.get(), base._root.get(), other._root.get(), context, trieKeyIndex);
_root->_count = other._root->_count + deltaCount;
_root->_dataSize = other._root->_dataSize + deltaDataSize;
}
// Iterators
const_iterator begin() const noexcept {
if (_root->isLeaf() && !_root->_data)
return end();
Node* node = _begin(_root.get());
return RadixStore::const_iterator(_root, node);
}
const_reverse_iterator rbegin() const noexcept {
return const_reverse_iterator(end());
}
const_iterator end() const noexcept {
return const_iterator(_root);
}
const_reverse_iterator rend() const noexcept {
return const_reverse_iterator(_root);
}
const_iterator find(const Key& key) const {
const_iterator it = RadixStore::end();
Node* node = _findNode(key);
if (node == nullptr)
return it;
else
return const_iterator(_root, node);
}
const_iterator lower_bound(const Key& key) const {
Node* node = _root.get();
const uint8_t* charKey = reinterpret_cast<const uint8_t*>(key.data());
std::vector<std::pair<Node*, uint8_t>> context;
size_t depth = 0;
// Traverse the path given the key to see if the node exists.
while (depth < key.size()) {
uint8_t idx = charKey[depth];
// When we go back up the tree to search for the lower bound of key, always search to
// the right of 'idx' so that we never search anything less than what the lower bound
// would be.
if (idx != UINT8_MAX)
context.push_back(std::make_pair(node, idx + 1));
if (!node->_children[idx])
break;
node = node->_children[idx].get();
size_t mismatchIdx =
_comparePrefix(node->_trieKey, charKey + depth, key.size() - depth);
// There is a prefix mismatch, so we don't need to traverse anymore.
if (mismatchIdx < node->_trieKey.size()) {
// Check if the current key in the tree is greater than the one we are looking
// for since it can't be equal at this point. It can be greater in two ways:
// It can be longer or it can have a larger character at the mismatch index.
uint8_t mismatchChar = charKey[mismatchIdx + depth];
if (mismatchIdx == key.size() - depth ||
node->_trieKey[mismatchIdx] > mismatchChar) {
// If the current key is greater and has a value it is the lower bound.
if (node->_data)
return const_iterator(_root, node);
// If the current key has no value, place it in the context
// so that we can search its children.
context.push_back(std::make_pair(node, 0));
}
break;
}
depth = node->_depth + node->_trieKey.size();
}
if (depth == key.size()) {
// If the node exists, then we can just return an iterator to that node.
if (node->_data)
return const_iterator(_root, node);
// The search key is an exact prefix, so we need to search all of this node's
// children.
context.back() = std::make_pair(node, 0);
}
// The node with the provided key did not exist. Now we must find the next largest node, if
// it exists.
while (!context.empty()) {
uint8_t idx = 0;
std::tie(node, idx) = context.back();
context.pop_back();
for (auto iter = idx + node->_children.begin(); iter != node->_children.end(); ++iter) {
if (!(*iter))
continue;
// There exists a node with a key larger than the one given.
node = iter->get();
if (node->_data)
return const_iterator(_root, node);
// Need to search this node's children for the next largest node.
context.push_back(std::make_pair(node, 0));
break;
}
if (node->_trieKey.empty() && context.empty()) {
// We have searched the root. There's nothing left to search.
return end();
}
}
// There was no node key at least as large as the one given.
return end();
}
const_iterator upper_bound(const Key& key) const {
const_iterator it = lower_bound(key);
if (it == end())
return it;
if (it->first == key)
return ++it;
return it;
}
typename RadixStore::iterator::difference_type distance(iterator iter1, iterator iter2) {
return std::distance(iter1, iter2);
}
typename RadixStore::iterator::difference_type distance(const_iterator iter1,
const_iterator iter2) {
return std::distance(iter1, iter2);
}
std::string to_string_for_test() {
return _walkTree(_root.get(), 0);
}
private:
class Node {
friend class RadixStore;
public:
Node() = default;
Node(std::vector<uint8_t> key) {
_trieKey = key;
}
Node(const Node& other) {
_trieKey = other._trieKey;
_depth = other._depth;
if (other._data)
_data.emplace(other._data->first, other._data->second);
_children = other._children;
}
Node(Node&& other) {
_depth = std::move(other._depth);
_trieKey = std::move(other._trieKey);
_data = std::move(other._data);
_children = std::move(other._children);
}
virtual ~Node() = default;
friend void swap(Node& first, Node& second) {
std::swap(first.trieKey, second.trieKey);
std::swap(first.depth, second.depth);
std::swap(first.data, second.data);
std::swap(first.children, second.children);
}
Node& operator=(const Node other) {
swap(*this, other);
return *this;
}
bool isLeaf() const {
for (auto child : _children) {
if (child != nullptr)
return false;
}
return true;
}
protected:
unsigned int _depth = 0;
std::vector<uint8_t> _trieKey;
boost::optional<value_type> _data;
std::array<std::shared_ptr<Node>, 256> _children;
};
/**
* Head is the root node of every RadixStore, it contains extra information used by cursors to
* be able to see when the tree is modified and to respond to these changes by ensuring they are
* not iterating over stale trees.
*/
class Head : public Node {
friend class RadixStore;
public:
Head() = default;
Head(std::vector<uint8_t> key) : Node(key) {}
Head(const Node& other) : Node(other) {}
Head(const Head& other) : Node(other), _count(other._count), _dataSize(other._dataSize) {}
~Head() {
if (_nextVersion)
_nextVersion->_hasPreviousVersion = false;
}
friend void swap(Head& first, Head& second) {
Node::swap(first, second);
}
Head(Head&& other) : Node(std::move(other)) {}
Head& operator=(const Head other) {
swap(*this, other);
return *this;
}
bool hasPreviousVersion() const {
return _hasPreviousVersion;
}
protected:
// Forms a singly linked list of versions that is needed to reposition cursors after
// modifications have been made.
std::shared_ptr<Head> _nextVersion;
// While we have cursors that haven't been repositioned to the latest tree, this will be
// true to help us understand when to copy on modifications due to the extra shared pointer
// _nextVersion.
bool _hasPreviousVersion = false;
private:
size_type _count = 0;
size_type _dataSize = 0;
};
/**
* Return a string representation of all the nodes in this tree.
* The string will look like:
*
* food
* s
* bar
*
* The number of spaces in front of each node indicates the depth
* at which the node lies.
*/
std::string _walkTree(Node* node, int depth) {
std::string ret;
for (int i = 0; i < depth; i++) {
ret.push_back(' ');
}
for (uint8_t ch : node->_trieKey) {
ret.push_back(ch);
}
if (node->_data) {
ret.push_back('*');
}
ret.push_back('\n');
for (auto child : node->_children) {
if (child != nullptr) {
ret.append(_walkTree(child.get(), depth + 1));
}
}
return ret;
}
Node* _findNode(const Key& key) const {
const uint8_t* charKey = reinterpret_cast<const uint8_t*>(key.data());
unsigned int depth = _root->_depth;
unsigned int initialDepthOffset = depth;
// If the root node's triekey is not empty then the tree is a subtree, and so we examine it.
for (unsigned int i = 0; i < _root->_trieKey.size(); i++) {
if (charKey[i + initialDepthOffset] != _root->_trieKey[i]) {
return nullptr;
}
depth++;
// Return node if entire trieKey matches.
if (depth == key.size() && _root->_data &&
(key.size() - initialDepthOffset) == _root->_trieKey.size()) {
return _root.get();
}
}
depth = _root->_depth + _root->_trieKey.size();
uint8_t childFirstChar = charKey[depth];
auto node = _root->_children[childFirstChar];
while (node != nullptr) {
depth = node->_depth;
size_t mismatchIdx =
_comparePrefix(node->_trieKey, charKey + depth, key.size() - depth);
if (mismatchIdx != node->_trieKey.size()) {
return nullptr;
} else if (mismatchIdx == key.size() - depth && node->_data) {
return node.get();
}
depth = node->_depth + node->_trieKey.size();
childFirstChar = charKey[depth];
node = node->_children[childFirstChar];
}
return nullptr;
}
/**
* Makes a copy of the _root node if it isn't uniquely owned during an operation that will
* modify the tree.
*
* The _root node wouldn't be uniquely owned only when there are cursors positioned on the
* latest version of the tree. Cursors that are not yet repositioned onto the latest version of
* the tree are not considered to be sharing the _root for modifying operations.
*/
void _makeRootUnique() {
int rootUseCount = _root->_hasPreviousVersion ? 2 : 1;
if (_root.use_count() == rootUseCount)
return;
invariant(_root.use_count() > rootUseCount);
// Copy the node on a modifying operation when the root isn't unique.
// There should not be any _nextVersion set in the _root otherwise our tree would have
// multiple HEADs.
invariant(!_root->_nextVersion);
_root->_nextVersion = std::make_shared<Head>(*_root);
_root = _root->_nextVersion;
_root->_hasPreviousVersion = true;
}
/**
* _upsertWithCopyOnSharedNodes is a helper function to help manage copy on modification for the
* tree. This function follows the path for the to-be modified node using the keystring. If at
* any point, the path is no longer uniquely owned, the following nodes are copied to prevent
* modification to other owner's data.