forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintrusive_btree.hh
2208 lines (1882 loc) · 70.3 KB
/
intrusive_btree.hh
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) 2021-present ScyllaDB
*/
/*
* SPDX-License-Identifier: LicenseRef-ScyllaDB-Source-Available-1.0
*/
#pragma once
#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/util/alloc_failure_injector.hh>
#include <cassert>
#include <fmt/core.h>
#include "utils/assert.hh"
#include "utils/collection-concepts.hh"
#include "utils/neat-object-id.hh"
#include "utils/allocation_strategy.hh"
namespace intrusive_b {
template <typename Func, typename T>
concept KeyCloner = requires (Func f, T* val) {
{ f(val) } -> std::same_as<T*>;
};
/*
* The KeyPointer is any wrapper that carries a "real" key one board and that
* can release it, thus giving its ownership to the tree. It's used in insert()
* methods where either key conflict or an exception may occur. In either case
* the key will not be released and freeing it is up to the caller.
*/
template <typename Pointer, typename T>
concept KeyPointer = std::is_nothrow_move_constructible_v<Pointer> &&
requires (Pointer p) { { *p } -> std::same_as<T&>; } &&
requires (Pointer p) { { p.release() } noexcept -> std::same_as<T*>; };
enum class with_debug { no, yes };
enum class key_search { linear, binary, both };
class member_hook;
// The LinearThreshold is explained below, see NODE_LINEAR flag
template <typename Key, member_hook Key::* Hook, typename Compare, size_t NodeSize, size_t LinearThreshold, key_search Search, with_debug Debug> class node;
template <typename Key, member_hook Key::*, typename Compare, size_t NodeSize, size_t LinearThreshold> class validator;
// For .{do_something_with_data}_and_dispose methods below
template <typename T>
void default_dispose(T* value) noexcept { }
using key_index = size_t;
using kid_index = size_t;
/*
* The key's member_hook must point to something that's independent from
* the tree's template parameters, so here's this base. It carries the
* bare minimum of information needed for member_hook to operate (see
* the iterator::erase()).
*/
class node_base {
template <typename K, member_hook K::* H, typename C, size_t NS, size_t LT, key_search KS, with_debug D> friend class node;
node_base(unsigned short n, unsigned short cap, unsigned short f) noexcept : num_keys(n), flags(f), capacity(cap) {}
public:
unsigned short num_keys;
unsigned short flags;
unsigned short capacity; // used by linear node only
/*
* Each node keeps pointers on keys, not their values. This allows keeping
* iterators valid after insert/remove.
*
* The size of this array is zero, because we don't know it. The real memory
* for it is reserved in class node.
*/
member_hook* keys[0];
static constexpr unsigned short NODE_ROOT = 0x1;
static constexpr unsigned short NODE_LEAF = 0x2;
static constexpr unsigned short NODE_LEFTMOST = 0x4; // leaf with smallest keys in the tree
static constexpr unsigned short NODE_RIGHTMOST = 0x8; // leaf with greatest keys in the tree
/*
* Linear node is the root leaf that grows above the NodeSize
* limit up to resching the LinearThreshold number of keys.
* After this the root leaf is shattered into a small tree,
* then B-tree works as usual.
*
* The backward (small tree -> linear node) transition is not
* performed, so the root leaf can be either linear, or regular,
* thus the explicit flag.
*/
static constexpr unsigned short NODE_LINEAR = 0x10;
/*
* Inline node is embedded into tree itself and is capabale
* of carrying a single key.
*/
static constexpr unsigned short NODE_INLINE = 0x20;
struct inline_tag{};
node_base(inline_tag) noexcept : num_keys(0), flags(NODE_ROOT | NODE_LEAF | NODE_INLINE), capacity(1) {}
bool is_root() const noexcept { return flags & NODE_ROOT; }
bool is_leaf() const noexcept { return flags & NODE_LEAF; }
bool is_leftmost() const noexcept { return flags & NODE_LEFTMOST; }
bool is_rightmost() const noexcept { return flags & NODE_RIGHTMOST; }
bool is_linear() const noexcept { return flags & NODE_LINEAR; }
bool is_inline() const noexcept { return flags & NODE_INLINE; }
node_base(const node_base&) = delete;
node_base(node_base&&) = delete;
key_index index_for(const member_hook* hook) const noexcept {
for (key_index i = 0; i < num_keys; i++) {
if (keys[i] == hook) {
return i;
}
}
std::abort();
}
bool empty() const noexcept { return num_keys == 0; }
private:
friend class member_hook;
void reattach(member_hook* to, member_hook* from) noexcept {
key_index idx = index_for(from);
keys[idx] = to;
}
};
/*
* Struct that's to be embedded into the key. Should be kept as small as possible.
*/
class member_hook {
template <typename K, member_hook K::* H, typename C, size_t NS, size_t LT> friend class validator;
template <typename K, member_hook K::* H, typename C, size_t NS, size_t LT, key_search KS, with_debug D> friend class node;
private:
node_base* _node = nullptr;
public:
bool attached() const noexcept { return _node != nullptr; }
node_base* node() const noexcept { return _node; }
void attach_first(node_base& to) noexcept {
SCYLLA_ASSERT(to.num_keys == 0);
to.num_keys = 1;
to.keys[0] = this;
_node = &to;
}
member_hook() noexcept = default;
member_hook(const member_hook&) = delete;
~member_hook() {
SCYLLA_ASSERT(!attached());
}
member_hook(member_hook&& other) noexcept : _node(other._node) {
if (attached()) {
_node->reattach(this, &other);
other._node = nullptr;
}
}
template <typename K, member_hook K::* Hook>
const K* to_key() const noexcept {
return boost::intrusive::get_parent_from_member(this, Hook);
}
template <typename K, member_hook K::* Hook>
K* to_key() noexcept {
return boost::intrusive::get_parent_from_member(this, Hook);
}
};
struct stats {
unsigned long nodes;
std::vector<unsigned long> nodes_filled;
unsigned long leaves;
std::vector<unsigned long> leaves_filled;
unsigned long linear_keys;
};
/*
* The tree itself.
* Equipped with constant time begin() and end() and the iterator, that
* scans through sorted keys and is not invalidated on insert/remove.
*
* The NodeSize parameter describes the amount of keys to be held on each
* node. Inner nodes will thus have N+1 pointers on sub-trees.
*/
template <typename Key, member_hook Key::* Hook, typename Compare, size_t NodeSize, size_t LinearThreshold, key_search Search, with_debug Debug = with_debug::no>
requires Comparable<Key, Key, Compare>
class tree {
// Sanity not to allow slow key-search in non-debug mode
static_assert(Debug == with_debug::yes || Search != key_search::both);
public:
friend class node<Key, Hook, Compare, NodeSize, LinearThreshold, Search, Debug>;
friend class validator<Key, Hook, Compare, NodeSize, LinearThreshold>;
using node = class node<Key, Hook, Compare, NodeSize, LinearThreshold, Search, Debug>;
class iterator;
class const_iterator;
private:
node* _root = nullptr;
struct corners {
node* left;
node* right;
corners() noexcept : left(nullptr), right(nullptr) {}
};
union {
corners _corners;
node_base _inline;
static_assert(sizeof(corners) >= sizeof(node_base) + sizeof(member_hook*));
};
static const tree* from_inline(const node_base* n) noexcept {
SCYLLA_ASSERT(n->is_inline());
return boost::intrusive::get_parent_from_member(n, &tree::_inline);
}
static tree* from_inline(node_base* n) noexcept {
SCYLLA_ASSERT(n->is_inline());
return boost::intrusive::get_parent_from_member(n, &tree::_inline);
}
/*
* Helper structure describing a position in a tree. Filled
* by key_lower_bound() method and is used by tree's API calls.
*/
struct cursor {
node* n;
kid_index idx;
void descend() noexcept {
n = n->_kids[idx];
__builtin_prefetch(n);
}
template <typename Pointer>
iterator insert(Pointer kptr) {
if (n->is_linear()) {
n = n->check_linear_capacity(idx);
}
Key& k = *kptr;
n->insert(idx, std::move(kptr));
/*
* We cannot trust cur.idx as insert might have moved
* it anywhere across the tree.
*/
return iterator(k.*Hook, 0);
}
};
/*
* Find the key in the tree or the position before which it should be
* and targets the cursor into this place. Returns true if the key
* itself was found, false otherwise.
*/
template <typename K>
bool key_lower_bound(const K& key, const Compare& cmp, cursor& cur) const {
cur.n = _root;
while (true) {
bool match;
cur.idx = cur.n->index_for(key, cmp, match);
SCYLLA_ASSERT(cur.idx <= cur.n->_base.num_keys);
if (match || cur.n->is_leaf()) {
return match;
}
cur.descend();
}
}
void do_set_root(node& n) noexcept {
SCYLLA_ASSERT(n.is_root());
n._parent.t = this;
_root = &n;
}
void do_set_left(node& n) noexcept {
SCYLLA_ASSERT(n.is_leftmost());
if (!n.is_linear()) {
n._leaf_tree = this;
}
_corners.left = &n;
}
void do_set_right(node& n) noexcept {
SCYLLA_ASSERT(n.is_rightmost());
if (!n.is_linear()) {
n._leaf_tree = this;
}
_corners.right = &n;
}
template <typename Pointer>
iterator insert_into_inline(Pointer kptr) noexcept {
member_hook* hook = &(kptr.release()->*Hook);
hook->attach_first(_inline);
return iterator(*hook, 0);
}
template <typename K>
std::strong_ordering find_in_inline(const K& k, const Compare& cmp) const {
return _inline.empty() ? std::strong_ordering::greater : cmp(k, *(_inline.keys[0]->to_key<Key, Hook>()));
}
void break_inline() {
node* n = node::create_empty_root();
_inline.keys[0]->attach_first(n->_base);
do_set_root(*n);
do_set_left(*n);
do_set_right(*n);
}
const node_base* rightmost_node() const noexcept {
return _root == nullptr ? &_inline : &_corners.right->_base;
}
node_base* rightmost_node() noexcept {
return _root == nullptr ? &_inline : &_corners.right->_base;
}
const node_base* leftmost_node() const noexcept {
return _root == nullptr ? &_inline : &_corners.left->_base;
}
node_base* leftmost_node() noexcept {
return _root == nullptr ? &_inline : &_corners.left->_base;
}
bool inline_root() const noexcept { return _root == nullptr; }
public:
tree() noexcept : _root(nullptr), _inline(node_base::inline_tag{}) {}
tree(tree&& other) noexcept : tree() {
if (!other.inline_root()) {
do_set_root(*other._root);
do_set_left(*other._corners.left);
do_set_right(*other._corners.right);
other._root = nullptr;
other._corners.left = nullptr;
other._corners.right = nullptr;
} else if (!other._inline.empty()) {
other._inline.keys[0]->attach_first(_inline);
other._inline.num_keys = 0;
}
}
tree(const tree& other) = delete;
~tree() noexcept {
if (!inline_root()) {
SCYLLA_ASSERT(_root->is_leaf());
node::destroy(*_root);
} else {
SCYLLA_ASSERT(_inline.empty());
}
}
template <typename Pointer>
requires KeyPointer<Pointer, Key>
std::pair<iterator, bool> insert(Pointer kptr, Compare cmp) {
seastar::memory::on_alloc_point();
cursor cur;
if (inline_root()) {
if (_inline.empty()) {
return std::pair(insert_into_inline(std::move(kptr)), true);
}
break_inline();
}
if (key_lower_bound(*kptr, cmp, cur)) {
return std::pair(iterator(cur), false);
}
return std::pair(cur.insert(std::move(kptr)), true);
}
/*
* Inserts the key into the tree using hint as an attempt not to lookup
* its position with logN algo. If the new key is hint - 1 <= key <= hint
* then the insertion goes in O(1) (amortizing rebalancing).
*/
template <typename Pointer>
requires KeyPointer<Pointer, Key>
std::pair<iterator, bool> insert_before_hint(iterator hint, Pointer kptr, Compare cmp) {
seastar::memory::on_alloc_point();
auto x = std::strong_ordering::less;
if (hint != end()) {
x = cmp(*kptr, *hint);
if (x == 0) {
return std::pair(iterator(hint), false);
}
}
if (x < 0) {
x = std::strong_ordering::greater;
if (hint != begin()) {
auto prev = std::prev(hint);
x = cmp(*kptr, *prev);
if (x == 0) {
return std::pair(iterator(prev), false);
}
}
if (x > 0) {
return std::pair(hint.insert_before(std::move(kptr)), true);
}
}
return insert(std::move(kptr), std::move(cmp));
}
/*
* Constant-time insertion right before the given position. No sorting
* is checked, the tree will be broken if the key/it are not in order.
*/
template <typename Pointer>
requires KeyPointer<Pointer, Key>
iterator insert_before(iterator it, Pointer kptr) {
seastar::memory::on_alloc_point();
return it.insert_before(std::move(kptr));
}
template <typename K>
requires Comparable<K, Key, Compare>
const_iterator find(const K& k, Compare cmp) const {
cursor cur;
if (inline_root()) {
if (find_in_inline(k, cmp) == 0) {
return const_iterator(*_inline.keys[0], 0);
}
return cend();
}
if (!key_lower_bound(k, cmp, cur)) {
return cend();
}
return const_iterator(cur);
}
template <typename K>
requires Comparable<K, Key, Compare>
iterator find(const K& k, Compare cmp) {
return iterator(const_cast<const tree*>(this)->find(k, cmp));
}
template <typename K>
requires Comparable<K, Key, Compare>
const_iterator lower_bound(const K& k, bool& match, Compare cmp) const {
if (inline_root()) {
auto x = find_in_inline(k, cmp);
if (x <= 0) {
match = x == 0;
return const_iterator(*_inline.keys[0], 0);
}
match = false;
return cend();
}
if (_root->_base.num_keys == 0) {
match = false;
return cend();
}
cursor cur;
match = key_lower_bound(k, cmp, cur);
if (!match && cur.idx == cur.n->_base.num_keys) {
SCYLLA_ASSERT(cur.idx > 0);
cur.idx--;
return ++const_iterator(cur);
}
return const_iterator(cur);
}
template <typename K>
requires Comparable<K, Key, Compare>
iterator lower_bound(const K& k, bool& match, Compare cmp) {
return iterator(const_cast<const tree*>(this)->lower_bound(k, match, cmp));
}
template <typename K>
requires Comparable<K, Key, Compare>
const_iterator lower_bound(const K& k, Compare cmp) const {
bool match;
return lower_bound(k, match, cmp);
}
template <typename K>
requires Comparable<K, Key, Compare>
iterator lower_bound(const K& k, Compare cmp) {
bool match;
return lower_bound(k, match, cmp);
}
template <typename K>
requires Comparable<K, Key, Compare>
const_iterator upper_bound(const K& k, Compare cmp) const {
bool match;
const_iterator ret = lower_bound(k, match, cmp);
if (match) {
ret++;
}
return ret;
}
template <typename K>
requires Comparable<K, Key, Compare>
iterator upper_bound(const K& k, Compare cmp) {
return iterator(const_cast<const tree*>(this)->upper_bound(k, cmp));
}
template <typename K, typename Disp>
requires Comparable<K, Key, Compare> && Disposer<Disp, Key>
iterator erase_and_dispose(const K& k, Compare cmp, Disp&& disp) {
cursor cur;
if (inline_root()) {
if (find_in_inline(k, cmp) == 0) {
node::dispose_key(_inline.keys[0], disp);
_inline.num_keys = 0;
}
return cend();
}
if (!key_lower_bound(k, cmp, cur)) {
return end();
}
iterator it(cur);
member_hook* hook = it._hook;
it++;
cur.n->remove(cur.idx);
node::dispose_key(hook, disp);
return it;
}
/*
* This range-erase is trivial and not optimal, each key erasure may
* end up rebalancing the upper nodes in vain.
*/
template <typename Disp>
requires Disposer<Disp, Key>
iterator erase_and_dispose(iterator from, iterator to, Disp&& disp) noexcept {
while (from != to) {
from = from.erase_and_dispose(disp);
}
return to;
}
template <typename Disp>
requires Disposer<Disp, Key>
iterator erase_and_dispose(const_iterator from, const_iterator to, Disp&& disp) noexcept {
return erase_and_dispose(iterator(from), iterator(to), std::forward<Disp>(disp));
}
template <typename Disp>
requires Disposer<Disp, Key>
iterator erase_and_dispose(iterator it, Disp&& disp) noexcept {
return it.erase_and_dispose(disp);
}
Key* unlink_leftmost_without_rebalance() noexcept {
node_base* nb = leftmost_node();
if (nb->num_keys == 0) {
return nullptr;
}
member_hook* hook = nb->keys[0];
node::dispose_key(hook, default_dispose<Key>);
if (nb->is_inline()) {
nb->num_keys = 0;
} else {
node* n = node::from_base(nb);
SCYLLA_ASSERT(n->is_leaf());
n->remove_leftmost_light_rebalance();
}
return hook->to_key<Key, Hook>();
}
template <typename... Args>
iterator erase(Args&&... args) { return erase_and_dispose(std::forward<Args>(args)..., default_dispose<Key>); }
template <typename Func>
requires Disposer<Func, Key>
void clear_and_dispose(Func&& disp) noexcept {
if (!inline_root()) {
_root->clear([&disp] (member_hook* h) { node::dispose_key(h, disp); });
node::destroy(*_root);
_root = nullptr;
// Both left and right leaves pointers are not touched as this
// initialization of inline node overwrites them anyway
new (&_inline) node_base(node_base::inline_tag{});
} else if (!_inline.empty()) {
node::dispose_key(_inline.keys[0], disp);
_inline.num_keys = 0;
}
}
void clear() noexcept { clear_and_dispose(default_dispose<Key>); }
/*
* Clone the tree using given Cloner (and Deleter for roll-back).
*/
template <typename Cloner, typename Deleter>
requires KeyCloner<Cloner, Key> && Disposer<Deleter, Key>
void clone_from(const tree& t, Cloner&& cloner, Deleter&& deleter) {
clear_and_dispose(deleter);
if (!t.inline_root()) {
node* left = nullptr;
node* right = nullptr;
_root = t._root->clone(left, right, cloner, deleter);
left->_base.flags |= node_base::NODE_LEFTMOST;
do_set_left(*left);
right->_base.flags |= node_base::NODE_RIGHTMOST;
do_set_right(*right);
_root->_base.flags |= node_base::NODE_ROOT;
do_set_root(*_root);
} else if (!t._inline.empty()) {
Key* key = cloner(t._inline.keys[0]->template to_key<Key, Hook>());
(key->*Hook).attach_first(_inline);
}
}
template <bool Const, typename Iterator> // Iterator will be derived from iterator_base
class iterator_base {
protected:
using tree_ptr = std::conditional_t<Const, const tree*, tree*>;
using key_hook_ptr = std::conditional_t<Const, const member_hook*, member_hook*>;
using node_base_ptr = std::conditional_t<Const, const node_base*, node_base*>;
using node_ptr = std::conditional_t<Const, const node*, node*>;
// The end() iterator uses _tree pointer, all the others use _hook.
union {
tree_ptr _tree;
key_hook_ptr _hook;
};
key_index _idx;
// No keys can be at this index, so it's used as the "end" mark.
static constexpr key_index npos = LinearThreshold;
explicit iterator_base(tree_ptr t) noexcept : _tree(t), _idx(npos) {}
iterator_base(key_hook_ptr h, key_index idx) noexcept : _hook(h), _idx(idx) {
SCYLLA_ASSERT(!is_end());
SCYLLA_ASSERT(h->attached());
}
explicit iterator_base(const cursor& cur) noexcept : _idx(cur.idx) {
SCYLLA_ASSERT(_idx < cur.n->_base.num_keys);
_hook = cur.n->_base.keys[_idx];
SCYLLA_ASSERT(_hook->attached());
}
iterator_base() noexcept : _tree(static_cast<tree_ptr>(nullptr)), _idx(npos) {}
bool is_end() const noexcept { return _idx == npos; }
/*
* The routine makes sure the iterator's index is valid
* and returns back the node that points to it.
*/
node_base_ptr revalidate() noexcept {
SCYLLA_ASSERT(!is_end());
node_base_ptr n = _hook->node();
/*
* The hook pointer is always valid (it's updated on insert/remove
* operations), the keys are not moved, so if the node still points
* at us, it is valid.
*/
if (_idx >= n->num_keys || n->keys[_idx] != _hook) {
_idx = n->index_for(_hook);
}
return n;
}
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = std::conditional_t<Const, const Key, Key>;
using difference_type = ssize_t;
using pointer = value_type*;
using reference = value_type&;
iterator_base(const iterator_base& other) noexcept {
if (other.is_end()) {
_idx = npos;
_tree = other._tree;
} else {
_idx = other._idx;
_hook = other._hook;
}
}
reference operator*() const noexcept { return *_hook->template to_key<Key, Hook>(); }
pointer operator->() const noexcept { return _hook->template to_key<Key, Hook>(); }
Iterator& operator++() noexcept {
node_base_ptr n = revalidate();
if (n->is_leaf()) [[likely]] {
if (_idx < n->num_keys - 1u) [[likely]] {
_idx++;
_hook = n->keys[_idx];
} else if (n->is_inline()) {
_idx = npos;
_tree = tree::from_inline(n);
} else if (n->is_rightmost()) {
_idx = npos;
_tree = node::from_base(n)->corner_tree();
} else {
node_ptr nd = node::from_base(n);
do {
node_ptr p = nd->_parent.n;
_idx = p->index_for(nd);
nd = p;
} while (_idx == nd->_base.num_keys);
_hook = nd->_base.keys[_idx];
}
} else {
node_ptr nd = node::from_base(n);
nd = nd->_kids[_idx + 1];
while (!nd->is_leaf()) {
nd = nd->_kids[0];
}
_idx = 0;
_hook = nd->_base.keys[_idx];
}
static_assert(std::is_base_of_v<iterator_base, Iterator>);
return static_cast<Iterator&>(*this);
}
Iterator& operator--() noexcept {
if (is_end()) {
node_base_ptr n = _tree->rightmost_node();
SCYLLA_ASSERT(n->num_keys > 0);
_idx = n->num_keys - 1u;
_hook = n->keys[_idx];
static_assert(std::is_base_of_v<iterator_base, Iterator>);
return static_cast<Iterator&>(*this);
}
node_ptr n = node::from_base(revalidate());
if (n->is_leaf()) {
while (_idx == 0) {
node_ptr p = n->_parent.n;
_idx = p->index_for(n);
n = p;
}
_idx--;
} else {
n = n->_kids[_idx];
while (!n->is_leaf()) {
n = n->_kids[n->_base.num_keys];
}
_idx = n->_base.num_keys - 1;
}
_hook = n->_base.keys[_idx];
static_assert(std::is_base_of_v<iterator_base, Iterator>);
return static_cast<Iterator&>(*this);
}
Iterator operator++(int) noexcept {
auto cur = Iterator(*this);
operator++();
return cur;
}
Iterator operator--(int) noexcept {
auto cur = Iterator(*this);
operator--();
return cur;
}
bool operator==(const iterator_base& o) const noexcept { return is_end() ? o.is_end() : _hook == o._hook; }
operator bool() const noexcept { return !is_end(); }
/*
* Special constructor for the case when there's the need for an
* iterator to the given value pointer. We can get all we need
* through the hook -> node_base -> node chain.
*/
iterator_base(pointer key) noexcept : iterator_base(&(key->*Hook), 0) {
revalidate();
}
/*
* Returns pointer on the owning tree if the element is the
* last one left in it.
*/
tree_ptr tree_if_singular() noexcept {
node_base* n = revalidate();
if (n->is_root() && n->is_leaf() && n->num_keys == 1) {
return n->is_inline() ? tree::from_inline(n) : node::from_base(n)->_parent.t;
} else {
return nullptr;
}
}
};
using iterator_base_const = iterator_base<true, const_iterator>;
using iterator_base_nonconst = iterator_base<false, iterator>;
class const_iterator final : public iterator_base_const {
friend class tree;
using super = iterator_base_const;
explicit const_iterator(const tree* t) noexcept : super(t) {}
explicit const_iterator(const cursor& cur) noexcept : super(cur) {}
const_iterator(const member_hook& h, key_index idx) noexcept : super(&h, idx) {}
public:
const_iterator() noexcept : super() {}
const_iterator(const iterator_base_const& other) noexcept : super(other) {}
const_iterator(const iterator& other) noexcept {
if (other.is_end()) {
super::_idx = super::npos;
super::_tree = const_cast<const tree*>(other._tree);
} else {
super::_idx = other._idx;
super::_hook = const_cast<const member_hook*>(other._hook);
}
}
};
class iterator final : public iterator_base_nonconst {
friend class tree;
friend class key_grabber;
using super = iterator_base_nonconst;
explicit iterator(const tree* t) noexcept : super(t) {}
explicit iterator(const cursor& cur) noexcept : super(cur) {}
iterator(member_hook& h, key_index idx) noexcept : super(&h, idx) {}
public:
iterator() noexcept : super() {}
iterator(const iterator_base_nonconst& other) noexcept : super(other) {}
iterator(const const_iterator& other) noexcept {
if (other.is_end()) {
super::_idx = super::npos;
super::_tree = const_cast<tree*>(other._tree);
} else {
super::_idx = other._idx;
super::_hook = const_cast<member_hook*>(other._hook);
}
}
private:
template <typename Disp>
requires Disposer<Disp, Key>
iterator erase_and_dispose(Disp&& disp) noexcept {
node_base* nb = super::revalidate();
iterator cur;
if (nb->is_inline()) {
cur._idx = super::npos;
cur._tree = tree::from_inline(nb);
nb->num_keys = 0;
} else {
cur = *this;
cur++;
node::from_base(nb)->remove(super::_idx);
if (cur._hook->node() == nb && cur._idx > 0) {
cur._idx--;
}
}
node::dispose_key(super::_hook, disp);
return cur;
}
template <typename Pointer>
iterator insert_before(Pointer kptr) {
cursor cur;
if (super::is_end()) {
tree* t = super::_tree;
if (t->inline_root()) {
if (t->_inline.empty()) {
return t->insert_into_inline(std::move(kptr));
}
t->break_inline();
}
cur.n = t->_corners.right;
cur.idx = cur.n->_base.num_keys;
} else {
node_base* n = super::revalidate();
if (n->is_inline()) {
tree* t = tree::from_inline(n);
t->break_inline();
cur.n = t->_root;
cur.idx = 0;
} else {
cur.n = node::from_base(n);
cur.idx = super::_idx;
while (!cur.n->is_leaf()) {
cur.descend();
cur.idx = cur.n->_base.num_keys;
}
}
}
return cur.insert(std::move(kptr));
}
};
bool empty() const noexcept { return inline_root() ? _inline.empty() : _root->_base.empty(); }
const_iterator cbegin() const noexcept {
const node_base* n = leftmost_node();
return n->num_keys == 0 ? cend() : const_iterator(*n->keys[0], 0);
}
const_iterator cend() const noexcept {
return const_iterator(this);
}
const_iterator begin() const noexcept { return cbegin(); }
const_iterator end() const noexcept { return cend(); }
iterator begin() noexcept {
return iterator(const_cast<const tree*>(this)->cbegin());
}
iterator end() noexcept {
return iterator(const_cast<const tree*>(this)->cend());
}
using reverse_iterator = std::reverse_iterator<iterator>;
reverse_iterator rbegin() noexcept { return std::make_reverse_iterator(end()); }
reverse_iterator rend() noexcept { return std::make_reverse_iterator(begin()); }
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
const_reverse_iterator crbegin() const noexcept { return std::make_reverse_iterator(cend()); }
const_reverse_iterator crend() const noexcept { return std::make_reverse_iterator(cbegin()); }
const_reverse_iterator rbegin() const noexcept { return crbegin(); }
const_reverse_iterator rend() const noexcept { return crend(); }
size_t calculate_size() const noexcept {
return inline_root() ? _inline.num_keys : _root->size_slow();
}
size_t external_memory_usage() const noexcept {
return inline_root() ? 0 : _root->external_memory_usage();
}
/*
* Helper to remove keys from trees using only the key iterator.
*
* Conforms to KeyPointer and can be used to move keys between trees.
* Create it with an iterator to a key in one tree and feed to some
* .insert method into the other. If the key will be taken by the
* target, it will be instantly removed from the source, and the
* original iterator will be updated as if it did i = src.erase(i).
*/
class key_grabber {
iterator& _it;
public:
explicit key_grabber(iterator& it) : _it(it) {
SCYLLA_ASSERT(!_it.is_end());
}
key_grabber(const key_grabber&) = delete;
key_grabber(key_grabber&&) noexcept = default;
Key& operator*() const noexcept { return *_it; }