forked from scylladb/scylladb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbptree.hh
1963 lines (1668 loc) · 61.6 KB
/
bptree.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) 2020-present ScyllaDB
*/
/*
* SPDX-License-Identifier: LicenseRef-ScyllaDB-Source-Available-1.0
*/
#pragma once
#include <boost/intrusive/parent_from_member.hpp>
#include <seastar/util/defer.hh>
#include <cassert>
#include <vector>
#include "utils/assert.hh"
#include "utils/allocation_strategy.hh"
#include "utils/collection-concepts.hh"
#include "utils/neat-object-id.hh"
#include "utils/array-search.hh"
namespace bplus {
enum class with_debug { no, yes };
/*
* Linear search in a sorted array of keys slightly beats the
* binary one on small sizes. For debugging purposes both methods
* should be used (and the result must coincide).
*/
enum class key_search { linear, binary, both };
/*
* The less-comparator can be any, but in trivial case when it is
* literally 'a < b' it may define the conversion of a lookup Key
* into a 64-bit integer type. Then the intra-node keys scan will
* use simd instructions.
*/
template <typename Key, typename Less>
concept SimpleLessCompare = requires (Less l, Key k) {
{ l.simplify_key(k) } noexcept -> std::same_as<int64_t>;
};
/*
* This wrapper prevents the value from being default-constructed
* when its container is created. The intended usage is to wrap
* elements of static arrays or containers with .emplace() methods
* that can live some time without the value in it.
*
* Similarly, the value is _not_ automatically destructed when this
* thing is, so ~Value() must be called by hand. For this there is the
* .remove() method and two helpers for common cases -- std::move-ing
* the value into another maybe-location (.emplace(maybe&&)) and
* constructing the new in place of the existing one (.replace(args...))
*/
template <typename Value, typename Less>
union maybe_key {
Value v;
/*
* When using simple lesser the avx searcher needs the unused keys
* to be set to minimal value (see comment in array_search_gt() why),
* so the default constructor and reset() need special implementation
* for this case
*/
template <typename L = Less>
requires (!SimpleLessCompare<Value, L>)
maybe_key() noexcept {}
template <typename L = Less>
requires (!SimpleLessCompare<Value, L>)
void reset() noexcept { v.~Value(); }
template <typename L = Less>
requires (SimpleLessCompare<Value, L>)
maybe_key() noexcept : v(utils::simple_key_unused_value) {}
template <typename L = Less>
requires (SimpleLessCompare<Value, L>)
void reset() noexcept { v = utils::simple_key_unused_value; }
~maybe_key() {}
maybe_key(const maybe_key&) = delete;
maybe_key(maybe_key&&) = delete;
/*
* Constructs the value inside the empty maybe wrapper.
*/
template <typename... Args>
void emplace(Args&&... args) noexcept {
new (&v) Value (std::forward<Args>(args)...);
}
/*
* The special-case handling of moving some other alive maybe-value.
* Calls the source destructor after the move.
*/
void emplace(maybe_key&& other) noexcept {
new (&v) Value(std::move(other.v));
other.reset();
}
/*
* Similar to emplace, but to be used on the alive maybe.
* Calls the destructor on it before constructing the new value.
*/
template <typename... Args>
void replace(Args&&... args) noexcept {
reset();
emplace(std::forward<Args>(args)...);
}
void replace(maybe_key&& other) = delete; // not to be called by chance
};
// For .{do_something_with_data}_and_dispose methods below
template <typename T>
void default_dispose(T* value) noexcept { }
/*
* Helper to explicitly capture all keys copying.
* Check test_key for more information.
*/
template <typename Key>
requires std::is_nothrow_copy_constructible_v<Key>
Key copy_key(const Key& other) noexcept {
return Key(other);
}
/*
* Consider a small 2-level tree like this
*
* [ . 5 . ]
* | |
* +------+ +-----+
* | |
* [ 1 . 2 . 3 . ] [ 5 . 6 . 7 . ]
*
* And we remove key 5 from it. First -- the key is removed
* from the leaf entry
*
* [ . 5 . ]
* | |
* +------+ +-----+
* | |
* [ 1 . 2 . 3 . ] [ 6 . 7. ]
*
* At this point we have a choice -- whether or not to update
* the separation key on the parent (root). Strictly speaking,
* the whole tree is correct now -- all the keys on the right
* are greater-or-equal than their separation key, though the
* "equal" never happens.
*
* This can be problematic if the keys are stored on data nodes
* and are referenced from the (non-)leaf nodes. In this case
* the separation key must be updated to point to some real key
* in its sub-tree.
*
* [ . 6 . ] <--- this key updated
* | |
* +------+ +-----+
* | |
* [ 1 . 2 . 3 . ] [ 6 . 7. ]
*
* As this update takes some time, this behaviour is tunable.
*
*/
constexpr bool strict_separation_key = true;
/*
* This is for testing, validator will be everybody's friend
* to have rights to check if the tree is internally correct.
*/
template <typename Key, typename T, typename Less, size_t NodeSize> class validator;
template <with_debug Debug> class statistics;
template <typename Key, typename T, typename Less, size_t NodeSize, key_search Search, with_debug Debug> class node;
template <typename Key, typename T, typename Less, size_t NodeSize, key_search Search, with_debug Debug> class data;
/*
* The tree itself.
* Equipped with O(1) (with little constant) 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 sub-trees,
* leaf nodes will have N data pointers.
*/
template <typename T, typename Key>
concept CanGetKeyFromValue = requires (T val) {
{ val.key() } -> std::same_as<Key>;
};
struct stats {
unsigned long nodes;
std::vector<unsigned long> nodes_filled;
unsigned long leaves;
std::vector<unsigned long> leaves_filled;
unsigned long datas;
};
template <typename Key, typename T, typename Less, size_t NodeSize,
key_search Search = key_search::binary, with_debug Debug = with_debug::no>
requires LessNothrowComparable<Key, Key, Less> &&
std::is_nothrow_move_constructible_v<Key> &&
std::is_nothrow_move_constructible_v<T>
class tree {
public:
class iterator;
class const_iterator;
friend class validator<Key, T, Less, NodeSize>;
friend class node<Key, T, Less, NodeSize, Search, Debug>;
// Sanity not to allow slow key-search in non-debug mode
static_assert(Debug == with_debug::yes || Search != key_search::both);
using node = class node<Key, T, Less, NodeSize, Search, Debug>;
using data = class data<Key, T, Less, NodeSize, Search, Debug>;
using kid_index = typename node::kid_index;
private:
node* _root = nullptr;
node* _left = nullptr;
node* _right = nullptr;
[[no_unique_address]] Less _less;
template <typename K>
node& find_leaf_for(const K& k) const noexcept {
node* cur = _root;
while (!cur->is_leaf()) {
kid_index i = cur->index_for(k, _less);
cur = cur->_kids[i].n;
}
return *cur;
}
void maybe_init_empty_tree() {
if (_root != nullptr) {
return;
}
node* n = node::create();
n->_flags |= node::NODE_LEAF | node::NODE_ROOT | node::NODE_RIGHTMOST | node::NODE_LEFTMOST;
do_set_root(n);
do_set_left(n);
do_set_right(n);
}
node* left_leaf_slow() const noexcept {
node* cur = _root;
while (!cur->is_leaf()) {
cur = cur->_kids[0].n;
}
return cur;
}
node* right_leaf_slow() const noexcept {
node* cur = _root;
while (!cur->is_leaf()) {
cur = cur->_kids[cur->_num_keys].n;
}
return cur;
}
template <typename K>
requires LessNothrowComparable<K, Key, Less>
const_iterator get_bound(const K& k, bool upper, bool& match) const noexcept {
match = false;
if (empty()) {
return end();
}
node& n = find_leaf_for(k);
kid_index i = n.index_for(k, _less);
/*
* Element at i (key at i - 1) is less or equal to the k,
* the next element is greater. Mind corner cases.
*/
if (i == 0) {
SCYLLA_ASSERT(n.is_leftmost());
return begin();
} else if (i <= n._num_keys) {
const_iterator cur = const_iterator(n._kids[i].d, i);
if (upper || _less(n._keys[i - 1].v, k)) {
cur++;
} else {
match = true;
}
return cur;
} else {
SCYLLA_ASSERT(n.is_rightmost());
return end();
}
}
template <typename K>
iterator get_bound(const K& k, bool upper, bool& match) noexcept {
return iterator(const_cast<const tree*>(this)->get_bound(k, upper, match));
}
public:
tree(const tree& other) = delete;
const tree& operator=(const tree& other) = delete;
tree& operator=(tree&& other) = delete;
explicit tree(Less less) noexcept : _less(less) { }
~tree() { clear(); }
Less less() const noexcept { return _less; }
tree(tree&& other) noexcept : _less(std::move(other._less)) {
if (other._root) {
do_set_root(other._root);
do_set_left(other._left);
do_set_right(other._right);
other._root = nullptr;
other._left = nullptr;
other._right = nullptr;
}
}
// XXX -- this uses linear scan over the leaf nodes
size_t size_slow() const noexcept {
if (_root == nullptr) {
return 0;
}
size_t ret = 0;
const node* leaf = _left;
while (1) {
SCYLLA_ASSERT(leaf->is_leaf());
ret += leaf->_num_keys;
if (leaf == _right) {
break;
}
leaf = leaf->get_next();
}
return ret;
}
// Returns result that is equal (both not less than each other)
template <typename K = Key>
requires LessNothrowComparable<K, Key, Less>
const_iterator find(const K& k) const noexcept {
if (empty()) {
return end();
}
node& n = find_leaf_for(k);
kid_index i = n.index_for(k, _less);
if (i >= 1 && !_less(n._keys[i - 1].v, k)) {
return const_iterator(n._kids[i].d, i);
} else {
return end();
}
}
template <typename K = Key>
requires LessNothrowComparable<K, Key, Less>
iterator find(const K& k) noexcept {
return iterator(const_cast<const tree*>(this)->find(k));
}
// Returns the least x out of those !less(x, k)
template <typename K = Key>
iterator lower_bound(const K& k) noexcept {
bool match;
return get_bound(k, false, match);
}
template <typename K = Key>
const_iterator lower_bound(const K& k) const noexcept {
bool match;
return get_bound(k, false, match);
}
template <typename K = Key>
iterator lower_bound(const K& k, bool& match) noexcept {
return get_bound(k, false, match);
}
template <typename K = Key>
const_iterator lower_bound(const K& k, bool& match) const noexcept {
return get_bound(k, false, match);
}
// Returns the least x out of those less(k, x)
template <typename K = Key>
iterator upper_bound(const K& k) noexcept {
bool match;
return get_bound(k, true, match);
}
template <typename K = Key>
const_iterator upper_bound(const K& k) const noexcept {
bool match;
return get_bound(k, true, match);
}
/*
* Constructs the element with key k inside the tree and returns
* iterator on it. If the key already exists -- just returns the
* iterator on it and sets the .second to false.
*/
template <typename... Args>
std::pair<iterator, bool> emplace(Key k, Args&&... args) {
maybe_init_empty_tree();
node& n = find_leaf_for(k);
kid_index i = n.index_for(k, _less);
if (i >= 1 && !_less(n._keys[i - 1].v, k)) {
// Direct hit
return std::pair(iterator(n._kids[i].d, i), false);
}
data* d = data::create(std::forward<Args>(args)...);
auto x = seastar::defer([&d] { data::destroy(*d, default_dispose<T>); });
n.insert(i, std::move(k), d, _less);
SCYLLA_ASSERT(d->attached());
x.cancel();
return std::pair(iterator(d, i + 1), true);
}
template <typename Func>
requires Disposer<Func, T>
iterator erase_and_dispose(const Key& k, Func&& disp) noexcept {
maybe_init_empty_tree();
node& n = find_leaf_for(k);
data* d;
kid_index i = n.index_for(k, _less);
if (i == 0) {
return end();
}
SCYLLA_ASSERT(n._num_keys > 0);
if (_less(n._keys[i - 1].v, k)) {
return end();
}
d = n._kids[i].d;
iterator it(d, i);
it++;
n.remove(i, _less);
data::destroy(*d, disp);
return it;
}
template <typename Func>
requires Disposer<Func, T>
iterator erase_and_dispose(iterator from, iterator to, Func&& disp) noexcept {
/*
* FIXME this is dog slow k*logN algo, need k+logN one
*/
while (from != to) {
from = from.erase_and_dispose(disp, _less);
}
return to;
}
template <typename... Args>
iterator erase(Args&&... args) noexcept { return erase_and_dispose(std::forward<Args>(args)..., default_dispose<T>); }
template <typename Func>
requires Disposer<Func, T>
void clear_and_dispose(Func&& disp) noexcept {
if (_root != nullptr) {
_root->clear(
[&disp] (data* d) noexcept { data::destroy(*d, disp); },
[] (node* n) noexcept { node::destroy(*n); }
);
node::destroy(*_root);
_root = nullptr;
_left = nullptr;
_right = nullptr;
}
}
void clear() noexcept { clear_and_dispose(default_dispose<T>); }
private:
void do_set_left(node *n) noexcept {
SCYLLA_ASSERT(n->is_leftmost());
_left = n;
n->_kids[0]._leftmost_tree = this;
}
void do_set_right(node *n) noexcept {
SCYLLA_ASSERT(n->is_rightmost());
_right = n;
n->_rightmost_tree = this;
}
void do_set_root(node *n) noexcept {
SCYLLA_ASSERT(n->is_root());
n->_root_tree = this;
_root = n;
}
public:
/*
* Iterator. Scans the datas in the sorted-by-key order.
* Is not invalidated by emplace/erase-s of other elements.
* Move constructors may turn the _idx invalid, but the
* .revalidate() method makes it good again.
*/
template <bool Const>
class iterator_base {
protected:
using tree_ptr = std::conditional_t<Const, const tree*, tree*>;
using data_ptr = std::conditional_t<Const, const data*, data*>;
using node_ptr = std::conditional_t<Const, const node*, node*>;
/*
* When the iterator gets to the end the _data is
* replaced with the _tree obtained from the right
* leaf, and the _idx is set to npos
*/
union {
tree_ptr _tree;
data_ptr _data;
};
kid_index _idx; // Index in leaf's _kids array pointing to _data
/*
* Leaf nodes cannot have kids (data nodes) at 0 position, so
* 0 is good for unsigned undefined position.
*/
static constexpr kid_index npos = 0;
bool is_end() const noexcept { return _idx == npos; }
explicit iterator_base(tree_ptr t) noexcept : _tree(t), _idx(npos) { }
iterator_base(data_ptr d, kid_index idx) noexcept : _data(d), _idx(idx) {
SCYLLA_ASSERT(!is_end());
}
iterator_base() noexcept : iterator_base(static_cast<tree_ptr>(nullptr)) {}
/*
* The routine makes sure the iterator's index is valid
* and returns back the leaf that points to it.
*/
node_ptr revalidate() noexcept {
SCYLLA_ASSERT(!is_end());
node_ptr leaf = _data->_leaf;
/*
* The data._leaf pointer is always valid (it's updated
* on insert/remove operations), the datas do not move
* as well, so if the leaf still points at us, it is valid.
*/
if (_idx > leaf->_num_keys || leaf->_kids[_idx].d != _data) {
_idx = leaf->index_for(_data);
}
return leaf;
}
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = std::conditional_t<Const, const T, T>;
using difference_type = ssize_t;
using pointer = value_type*;
using reference = value_type&;
reference operator*() const noexcept { return _data->value; }
pointer operator->() const noexcept { return &_data->value; }
iterator_base& operator++() noexcept {
node_ptr leaf = revalidate();
if (_idx < leaf->_num_keys) {
_idx++;
} else {
if (leaf->is_rightmost()) {
_idx = npos;
_tree = leaf->_rightmost_tree;
return *this;
}
leaf = leaf->get_next();
_idx = 1;
}
_data = leaf->_kids[_idx].d;
return *this;
}
iterator_base& operator--() noexcept {
if (is_end()) {
node* n = _tree->_right;
SCYLLA_ASSERT(n->_num_keys > 0);
_data = n->_kids[n->_num_keys].d;
_idx = n->_num_keys;
return *this;
}
node_ptr leaf = revalidate();
if (_idx > 1) {
_idx--;
} else {
leaf = leaf->get_prev();
_idx = leaf->_num_keys;
}
_data = leaf->_kids[_idx].d;
return *this;
}
iterator_base operator++(int) noexcept {
iterator_base cur = *this;
operator++();
return cur;
}
iterator_base operator--(int) noexcept {
iterator_base cur = *this;
operator--();
return cur;
}
bool operator==(const iterator_base& o) const noexcept { return is_end() ? o.is_end() : _data == o._data; }
};
using iterator_base_const = iterator_base<true>;
using iterator_base_nonconst = iterator_base<false>;
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) {}
const_iterator(const data* d, kid_index idx) noexcept : super(d, idx) {}
public:
const_iterator() noexcept : super() {}
};
class iterator final : public iterator_base_nonconst {
friend class tree;
using super = iterator_base_nonconst;
explicit iterator(tree* t) noexcept : super(t) {}
iterator(data* d, kid_index idx) noexcept : super(d, idx) {}
public:
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::_data = const_cast<data *>(other._data);
}
}
iterator() noexcept : super() {}
/*
* Special constructor for the case when there's the need for an
* iterator to the given value pointer. In this case we need to
* get three things:
* - pointer on class data: we assume that the value pointer
* is indeed embedded into the data and do the "container_of"
* maneuver
* - index at which the data is seen on the leaf: use the
* standard revalidation. Note, that we start with index 1
* which gives us 1/NodeSize chance of hitting the right index
* right at once :)
* - the tree itself: the worst thing here, creating an iterator
* like this is logN operation
*/
explicit iterator(T* value) noexcept
: super(boost::intrusive::get_parent_from_member(value, &data::value), 1) {
super::revalidate();
}
/*
* The key _MUST_ be in order and not exist,
* neither of those is checked
*/
template <typename KeyFn, typename... Args>
iterator emplace_before(KeyFn key, Less less, Args&&... args) {
node* leaf;
kid_index i;
if (!super::is_end()) {
leaf = super::revalidate();
i = super::_idx - 1;
if (i == 0 && !leaf->is_leftmost()) {
/*
* If we're about to insert a key before the 0th one, then
* we must make sure the separation keys from upper layers
* will separate the new key as well. If they won't then we
* should select the left sibling for insertion.
*
* For !strict_separation_key the solution is simple -- the
* upper level separation keys match the current 0th one, so
* we always switch to the left sibling.
*
* If we're already on the left-most leaf -- just insert, as
* there's no separatio key above it.
*/
static_assert(strict_separation_key);
leaf = leaf->get_prev();
i = leaf->_num_keys;
}
} else {
super::_tree->maybe_init_empty_tree();
leaf = super::_tree->_right;
i = leaf->_num_keys;
}
SCYLLA_ASSERT(i >= 0);
data* d = data::create(std::forward<Args>(args)...);
auto x = seastar::defer([&d] { data::destroy(*d, default_dispose<T>); });
leaf->insert(i, std::move(key(d)), d, less);
SCYLLA_ASSERT(d->attached());
x.cancel();
/*
* XXX -- if the node was not split we can ++ it index
* and keep iterator valid :)
*/
return iterator(d, i + 1);
}
template <typename... Args>
iterator emplace_before(Key k, Less less, Args&&... args) {
return emplace_before([&k] (data*) -> Key { return std::move(k); },
less, std::forward<Args>(args)...);
}
template <typename... Args>
requires CanGetKeyFromValue<T, Key>
iterator emplace_before(Less less, Args&&... args) {
return emplace_before([] (data* d) -> Key { return d->value.key(); },
less, std::forward<Args>(args)...);
}
private:
/*
* Prepare a likely valid iterator for the next element.
* Likely means, that unless removal starts rebalancing
* datas the _idx will be for the correct pointer.
*
* This is just like the operator++, with the exception
* that staying on the leaf doesn't increase the _idx, as
* in this case the next element will be shifted left to
* the current position.
*/
iterator next_after_erase(node* leaf) const noexcept {
if (super::_idx < leaf->_num_keys) {
return iterator(leaf->_kids[super::_idx + 1].d, super::_idx);
}
if (leaf->is_rightmost()) {
return iterator(leaf->_rightmost_tree);
}
leaf = leaf->get_next();
return iterator(leaf->_kids[1].d, 1);
}
public:
template <typename Func>
requires Disposer<Func, T>
iterator erase_and_dispose(Func&& disp, Less less) noexcept {
node* leaf = super::revalidate();
iterator cur = next_after_erase(leaf);
leaf->remove(super::_idx, less);
data::destroy(*super::_data, disp);
return cur;
}
iterator erase(Less less) { return erase_and_dispose(default_dispose<T>, less); }
template <typename... Args>
requires DynamicObject<T>
void reconstruct(size_t new_payload_size, Args&&... args) {
size_t new_size = super::_data->storage_size(new_payload_size);
node* leaf = super::revalidate();
auto ptr = current_allocator().alloc<data>(new_size);
data *dat, *cur = super::_data;
try {
dat = new (ptr) data(std::forward<Args>(args)...);
} catch(...) {
current_allocator().free(ptr, new_size);
throw;
}
dat->_leaf = leaf;
cur->_leaf = nullptr;
super::_data = dat;
leaf->_kids[super::_idx].d = dat;
current_allocator().destroy(cur);
}
};
const_iterator begin() const noexcept {
if (empty()) {
return end();
}
SCYLLA_ASSERT(_left->_num_keys > 0);
// Leaf nodes have data pointers starting from index 1
return const_iterator(_left->_kids[1].d, 1);
}
const_iterator end() const noexcept { return const_iterator(this); }
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
const_reverse_iterator rbegin() const noexcept { return std::make_reverse_iterator(end()); }
const_reverse_iterator rend() const noexcept { return std::make_reverse_iterator(begin()); }
iterator begin() noexcept { return iterator(const_cast<const tree*>(this)->begin()); }
iterator end() noexcept { return iterator(this); }
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()); }
bool empty() const noexcept { return _root == nullptr || _root->_num_keys == 0; }
struct stats get_stats() const noexcept {
struct stats st;
st.nodes = 0;
st.leaves = 0;
st.datas = 0;
if (_root != nullptr) {
st.nodes_filled.resize(NodeSize + 1);
st.leaves_filled.resize(NodeSize + 1);
_root->fill_stats(st);
}
return st;
}
};
/*
* Algorithms for searching a key in array.
*
* The gt() method accepts sorted array of keys and searches the index of the
* upper-bound element of the given key.
*/
template <typename K, typename Key, typename Less, size_t Size, key_search Search>
struct searcher { };
template <typename K, typename Key, typename Less, size_t Size>
struct searcher<K, Key, Less, Size, key_search::linear> {
static size_t gt(const K& k, const maybe_key<Key, Less>* keys, size_t nr, Less less) noexcept {
size_t i;
for (i = 0; i < nr; i++) {
if (less(k, keys[i].v)) {
break;
}
}
return i;
};
};
template <typename K, typename Less, size_t Size>
requires SimpleLessCompare<K, Less>
struct searcher<K, int64_t, Less, Size, key_search::linear> {
static_assert(sizeof(maybe_key<int64_t, Less>) == sizeof(int64_t));
static size_t gt(const K& k, const maybe_key<int64_t, Less>* keys, size_t nr, Less less) noexcept {
return utils::array_search_gt(less.simplify_key(k), reinterpret_cast<const int64_t*>(keys), Size, nr);
}
};
template <typename K, typename Key, typename Less, size_t Size>
struct searcher<K, Key, Less, Size, key_search::binary> {
static size_t gt(const K& k, const maybe_key<Key, Less>* keys, size_t nr, Less less) noexcept {
ssize_t s = 0, e = nr - 1; // signed for below s <= e corner cases
while (s <= e) {
size_t i = (s + e) / 2;
if (less(k, keys[i].v)) {
e = i - 1;
} else {
s = i + 1;
}
}
return s;
}
};
template <typename K, typename Key, typename Less, size_t Size>
struct searcher<K, Key, Less, Size, key_search::both> {
static size_t gt(const K& k, const maybe_key<Key, Less>* keys, size_t nr, Less less) noexcept {
size_t rl = searcher<K, Key, Less, Size, key_search::linear>::gt(k, keys, nr, less);
size_t rb = searcher<K, Key, Less, Size, key_search::binary>::gt(k, keys, nr, less);
SCYLLA_ASSERT(rl == rb);
SCYLLA_ASSERT(rl <= nr);
return rl;
}
};
/*
* A node describes both, inner and leaf nodes.
*/
template <typename Key, typename T, typename Less, size_t NodeSize, key_search Search, with_debug Debug>
class node final {
friend class validator<Key, T, Less, NodeSize>;
friend class tree<Key, T, Less, NodeSize, Search, Debug>;
friend class data<Key, T, Less, NodeSize, Search, Debug>;
using tree = class tree<Key, T, Less, NodeSize, Search, Debug>;
using data = class data<Key, T, Less, NodeSize, Search, Debug>;
class prealloc;
/*
* The NodeHalf is the level at which the node is considered
* to be underflown and should be re-filled. This slightly
* differs for even and odd sizes.
*
* For odd sizes the node will stand until it contains literally
* more than 1/2 of it's size (e.g. for size 5 keeping 3 keys
* is OK). For even cases this barrier is less than the actual
* half (e.g. for size 4 keeping 2 is still OK).
*/
static constexpr size_t NodeHalf = ((NodeSize - 1) / 2);
static_assert(NodeHalf >= 1);
union node_or_data_or_tree {
node* n;
data* d;
tree* _leftmost_tree; // See comment near node::__next about this
};
using node_or_data = node_or_data_or_tree;
[[no_unique_address]] utils::neat_id<Debug == with_debug::yes> id;
unsigned short _num_keys;
unsigned short _flags;
static const unsigned short NODE_ROOT = 0x1;
static const unsigned short NODE_LEAF = 0x2;
static const unsigned short NODE_LEFTMOST = 0x4; // leaf with smallest keys in the tree
static const unsigned short NODE_RIGHTMOST = 0x8; // leaf with greatest keys in the tree
bool is_leaf() const noexcept { return _flags & NODE_LEAF; }
bool is_root() const noexcept { return _flags & NODE_ROOT; }
bool is_rightmost() const noexcept { return _flags & NODE_RIGHTMOST; }
bool is_leftmost() const noexcept { return _flags & NODE_LEFTMOST; }
/*
* separation keys
* non-leaf nodes:
* keys in kids[i] < keys[i] <= keys in kids[i+1], i in [0, NodeSize)
* leaf nodes:
* kids[i + 1] is the data for keys[i]
* kids[0] is unused
*
* In the examples below the leaf nodes will be shown like
*
* keys: [012]
* datas: [-012]
*
* and the non-leaf ones like
*
* keys: [012]
* kids: [A012]
*