Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
tpl_bplus_tree.H
Go to the documentation of this file.
1/*
2 Aleph_w
3
4 Data structures & Algorithms
5 version 2.0.0b
6 https://github.com/lrleon/Aleph-w
7
8 This file is part of Aleph-w library
9
10 Copyright (c) 2002-2026 Leandro Rabindranath Leon
11
12 Permission is hereby granted, free of charge, to any person obtaining a copy
13 of this software and associated documentation files (the "Software"), to deal
14 in the Software without restriction, including without limitation the rights
15 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
16 copies of the Software, and to permit persons to whom the Software is
17 furnished to do so, subject to the following conditions:
18
19 The above copyright notice and this permission notice shall be included in all
20 copies or substantial portions of the Software.
21
22 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
23 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
24 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
25 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
26 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
27 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
28 SOFTWARE.
29*/
30
49#ifndef TPL_BPLUS_TREE_H
50#define TPL_BPLUS_TREE_H
51
52#include <algorithm>
53#include <concepts>
54#include <initializer_list>
55#include <iterator>
56#include <memory>
57#include <optional>
58#include <type_traits>
59#include <utility>
60
61#include <ah-concepts.H>
62#include <ah-errors.H>
63#include <ahFunction.H>
64#include <tpl_array.H>
65#include <tpl_sort_utils.H>
66
67namespace Aleph {
68namespace detail {
69template <typename Compare, typename Key>
70[[nodiscard]] bool bplus_equiv(const Compare &cmp, const Key &lhs, const Key &rhs)
71{
72 return not cmp(lhs, rhs) and not cmp(rhs, lhs);
73}
74
75template <typename Key> struct BPlusTreeNode
76{
77 bool leaf = true;
80 BPlusTreeNode *next = nullptr;
81
82 explicit BPlusTreeNode(const bool is_leaf) : leaf(is_leaf) {}
83};
84} // namespace detail
85
133template <typename Key, class Compare = Aleph::less<Key>, size_t MinDegree = 16>
134 requires StrictWeakOrder<Compare, Key>
136{
137 static_assert(MinDegree >= 2, "BPlus_Tree requires MinDegree >= 2");
138 static_assert(std::copy_constructible<Key>, "BPlus_Tree requires copy-constructible keys");
139
141
142 static constexpr size_t MaxKeys = 2 * MinDegree - 1;
143 static constexpr size_t MinKeys = MinDegree - 1;
144
145 std::unique_ptr<Node> root_;
146 size_t size_ = 0;
147 Compare cmp_;
148
149 [[nodiscard]] size_t lower_bound_index(const Array<Key> &keys, const Key &key) const
150 {
151 size_t idx = 0;
152 while (idx < keys.size() and cmp_(keys[idx], key))
153 ++idx;
154 return idx;
155 }
156
157 [[nodiscard]] size_t upper_bound_index(const Array<Key> &keys, const Key &key) const
158 {
159 size_t idx = 0;
160 while (idx < keys.size() and (cmp_(keys[idx], key) or equals(keys[idx], key)))
161 ++idx;
162 return idx;
163 }
164
165 [[nodiscard]] size_t child_index(const Node *node, const Key &key) const
166 {
167 return upper_bound_index(node->keys, key);
168 }
169
170 [[nodiscard]] bool equals(const Key &lhs, const Key &rhs) const
171 {
172 return detail::bplus_equiv(cmp_, lhs, rhs);
173 }
174
175 [[nodiscard]] bool strictly_sorted(const Array<Key> &keys) const
176 {
177 for (size_t i = 1; i < keys.size(); ++i)
178 if (not cmp_(keys[i - 1], keys[i]))
179 return false;
180 return true;
181 }
182
183 template <std::input_iterator It> void insert_range(It first, It last)
184 {
185 for (; first != last; ++first)
186 insert(*first);
187 }
188
189 template <typename T, typename U> static void insert_at(Array<T> &array, const size_t idx, U &&value)
190 {
191 if (idx == array.size())
192 {
193 array.append(std::forward<U>(value));
194 return;
195 }
196
197 array.putn(1);
198 T *base = &array[0];
199 Aleph::open_gap(base, array.size(), idx, 1);
200 array(idx) = std::forward<U>(value);
201 }
202
203 template <typename T> static T erase_at(Array<T> &array, const size_t idx)
204 {
205 T ret = std::move(array(idx));
206 if (idx + 1 < array.size())
207 {
208 T *base = &array[0];
209 Aleph::close_gap(base, array.size(), idx, 1);
210 }
211 (void) array.remove_last();
212 return ret;
213 }
214
215 template <typename T> static void truncate(Array<T> &array, const size_t new_size)
216 {
217 while (array.size() > new_size)
218 (void) array.remove_last();
219 }
220
221 template <typename T> static void append_copy_range(Array<T> &dst, const Array<T> &src, const size_t from)
222 {
223 dst.reserve(dst.size() + src.size() - from);
224 for (size_t i = from; i < src.size(); ++i)
225 dst.append(src[i]);
226 }
227
228 template <typename T> static void append_move_range(Array<T> &dst, Array<T> &src, const size_t from)
229 {
230 dst.reserve(dst.size() + src.size() - from);
231 for (size_t i = from; i < src.size(); ++i)
232 dst.append(std::move(src(i)));
233 }
234
235 [[nodiscard]] const Node *leftmost_leaf(const Node *node) const noexcept
236 {
237 const Node *curr = node;
238 while (curr != nullptr and not curr->leaf)
239 curr = curr->children.get_first().get();
240 return curr;
241 }
242
243 [[nodiscard]] const Node *rightmost_leaf(const Node *node) const noexcept
244 {
245 const Node *curr = node;
246 while (curr != nullptr and not curr->leaf)
247 curr = curr->children.get_last().get();
248 return curr;
249 }
250
251 [[nodiscard]] const Key *subtree_min_ptr(const Node *node) const noexcept
252 {
253 const Node *leaf = leftmost_leaf(node);
254 if (leaf == nullptr or leaf->keys.is_empty())
255 return nullptr;
256 return &leaf->keys.get_first();
257 }
258
259 [[nodiscard]] const Key *subtree_max_ptr(const Node *node) const noexcept
260 {
261 const Node *leaf = rightmost_leaf(node);
262 if (leaf == nullptr or leaf->keys.is_empty())
263 return nullptr;
264 return &leaf->keys.get_last();
265 }
266
267 [[nodiscard]] const Key &subtree_min(const Node *node) const
268 {
269 const Key *ptr = subtree_min_ptr(node);
270 ah_runtime_error_unless(ptr != nullptr) << "BPlus_Tree invariant violated: empty subtree has no minimum";
271 return *ptr;
272 }
273
274 [[nodiscard]] size_t height_of(const Node *node) const noexcept
275 {
276 size_t height = 0;
277 for (const Node *curr = node; curr != nullptr;)
278 {
279 ++height;
280 if (curr->leaf or curr->children.is_empty())
281 break;
282 curr = curr->children.get_first().get();
283 }
284 return height;
285 }
286
287 void rebuild_separators(Node *node) const
288 {
289 if (node == nullptr or node->leaf)
290 return;
291
292 node->keys.empty();
293 node->keys.reserve(node->children.size() > 0 ? node->children.size() - 1 : 0);
294 for (size_t i = 1; i < node->children.size(); ++i)
295 node->keys.append(subtree_min(node->children[i].get()));
296 }
297
298 [[nodiscard]] std::unique_ptr<Node> clone_node(const Node *node, Node *&prev_leaf) const
299 {
300 if (node == nullptr)
301 return nullptr;
302
303 auto copy = std::make_unique<Node>(node->leaf);
304 copy->keys = node->keys;
305
306 if (node->leaf)
307 {
308 if (prev_leaf != nullptr)
309 prev_leaf->next = copy.get();
310 prev_leaf = copy.get();
311 return copy;
312 }
313
314 copy->children.reserve(node->children.size());
315 for (const auto &child : node->children)
316 copy->children.append(clone_node(child.get(), prev_leaf));
318 return copy;
319 }
320
321 [[nodiscard]] const Node *find_leaf(const Key &key) const
322 {
323 const Node *curr = root_.get();
324 while (curr != nullptr and not curr->leaf)
325 curr = curr->children[child_index(curr, key)].get();
326 return curr;
327 }
328
329 [[nodiscard]] bool contains_in(const Node *node, const Key &key) const
330 {
331 if (node == nullptr)
332 return false;
333
334 const Node *leaf = find_leaf(key);
335 if (leaf == nullptr)
336 return false;
337
338 const size_t idx = lower_bound_index(leaf->keys, key);
339 return idx < leaf->keys.size() and equals(leaf->keys[idx], key);
340 }
341
342 // Split the full child idx of parent. All that can throw is done before
343 // the tree changes: the new node with the upper half (its keys, or room
344 // for its children), the lower half of the child, the separators of the
345 // three nodes and room in the parent; then the arrays are exchanged and
346 // the pointers moved, which does not throw. It truncated the child first,
347 // so a failure after that lost the keys of the new node: and the whole
348 // tree, when insert() split a full root.
349 void split_child(Node *parent, const size_t idx)
350 {
351 Node *child = parent->children[idx].get();
352 auto right = std::make_unique<Node>(child->leaf);
353 Array<Key> child_keys;
354 Array<std::unique_ptr<Node>> child_children;
355 if (child->leaf)
356 {
357 append_copy_range(right->keys, child->keys, MinKeys);
358 child_keys.reserve(MaxKeys);
359 for (size_t i = 0; i < MinKeys; ++i)
360 child_keys.append(child->keys[i]);
361 }
362 else
363 {
364 right->children.reserve(child->children.size() - MinDegree);
365 child_children.reserve(2 * MinDegree);
366 child_keys.reserve(MaxKeys);
367 for (size_t i = 1; i < MinDegree; ++i)
368 child_keys.append(subtree_min(child->children[i].get()));
369 right->keys.reserve(MaxKeys);
370 for (size_t i = MinDegree + 1; i < child->children.size(); ++i)
371 right->keys.append(subtree_min(child->children[i].get()));
372 }
373
374 Array<Key> parent_keys; // the separators of the children after the split
375 parent_keys.reserve(parent->children.size());
376 for (size_t i = 1; i <= idx; ++i)
377 parent_keys.append(subtree_min(parent->children[i].get()));
378 parent_keys.append(child->leaf ? child->keys[MinKeys]
379 : subtree_min(child->children[MinDegree].get()));
380 for (size_t i = idx + 1; i < parent->children.size(); ++i)
381 parent_keys.append(subtree_min(parent->children[i].get()));
382 parent->children.reserve(parent->children.size() + 1);
383
384 if (child->leaf)
385 {
386 right->next = child->next;
387 child->next = right.get();
388 }
389 else
390 {
391 for (size_t i = 0; i < child->children.size(); ++i)
392 (i < MinDegree ? child_children : right->children).append(std::move(child->children(i)));
393 child->children.swap(child_children);
394 }
395 child->keys.swap(child_keys);
396 insert_at(parent->children, idx + 1, std::move(right));
397 parent->keys.swap(parent_keys);
398 }
399
400 void insert_nonfull(Node *node, const Key &key)
401 {
402 if (node->leaf)
403 {
404 // The copy is made before the keys move, so one that throws leaves
405 // them as they were
406 Key copy = key;
407 insert_at(node->keys, lower_bound_index(node->keys, key), std::move(copy));
408 return;
409 }
410
411 size_t idx = child_index(node, key);
412 if (node->children[idx]->keys.size() == MaxKeys)
413 {
414 split_child(node, idx);
415 idx = child_index(node, key);
416 }
417
418 // No separator changes below a split: a key that goes to the child
419 // i > 0 is greater than its least key, separator i - 1. Rebuilding them
420 // on the way back copied all of them at each level, and a copy that
421 // threw left the node without them
422 insert_nonfull(node->children[idx].get(), key);
423 }
424
425 void borrow_from_prev(Node *parent, const size_t idx)
426 {
427 Node *child = parent->children[idx].get();
428 Node *left = parent->children[idx - 1].get();
429
430 if (child->leaf)
431 {
432 insert_at(child->keys, 0, left->keys.get_last());
433 (void) left->keys.remove_last();
434 }
435 else
436 {
437 insert_at(child->children, 0, std::move(left->children.get_last()));
438 (void) left->children.remove_last();
439 rebuild_separators(left);
440 rebuild_separators(child);
441 }
442
443 rebuild_separators(parent);
444 }
445
446 void borrow_from_next(Node *parent, const size_t idx)
447 {
448 Node *child = parent->children[idx].get();
449 Node *right = parent->children[idx + 1].get();
450
451 if (child->leaf)
452 {
453 child->keys.append(right->keys.get_first());
454 erase_at(right->keys, 0);
455 }
456 else
457 {
458 child->children.append(std::move(right->children.get_first()));
459 erase_at(right->children, 0);
460 rebuild_separators(child);
461 rebuild_separators(right);
462 }
463
464 rebuild_separators(parent);
465 }
466
467 void merge_children(Node *parent, const size_t left_idx)
468 {
469 Node *left = parent->children[left_idx].get();
470 auto right = std::move(parent->children[left_idx + 1]);
471
472 if (left->leaf)
473 {
474 append_copy_range(left->keys, right->keys, 0);
475 left->next = right->next;
476 }
477 else
478 {
479 append_move_range(left->children, right->children, 0);
480 rebuild_separators(left);
481 }
482
483 erase_at(parent->children, left_idx + 1);
484 rebuild_separators(parent);
485 }
486
487 void fix_underflow(Node *parent, const size_t idx)
488 {
489 if (parent->children[idx]->keys.size() >= MinKeys)
490 {
491 rebuild_separators(parent);
492 return;
493 }
494
495 if (idx > 0 and parent->children[idx - 1]->keys.size() > MinKeys)
496 {
497 borrow_from_prev(parent, idx);
498 return;
499 }
500
501 if (idx + 1 < parent->children.size() and parent->children[idx + 1]->keys.size() > MinKeys)
502 {
503 borrow_from_next(parent, idx);
504 return;
505 }
506
507 if (idx + 1 < parent->children.size())
508 merge_children(parent, idx);
509 else
510 merge_children(parent, idx - 1);
511 }
512
513 [[nodiscard]] bool remove_from(Node *node, const Key &key)
514 {
515 if (node->leaf)
516 {
517 const size_t idx = lower_bound_index(node->keys, key);
518 if (idx >= node->keys.size() or not equals(node->keys[idx], key))
519 return false;
520
521 erase_at(node->keys, idx);
522 return true;
523 }
524
525 const size_t idx = child_index(node, key);
526 if (const bool removed = remove_from(node->children[idx].get(), key); not removed)
527 return false;
528
529 fix_underflow(node, idx);
530 rebuild_separators(node);
531 return true;
532 }
533
534 [[nodiscard]] bool verify_leaf_chain() const
535 {
536 const Node *leaf = leftmost_leaf(root_.get());
537 size_t counted = 0;
538 std::optional<Key> prev;
539
540 while (leaf != nullptr)
541 {
542 if (not leaf->leaf or leaf->keys.is_empty())
543 return false;
544
545 for (const auto &key : leaf->keys)
546 {
547 if (prev.has_value() and not cmp_(*prev, key))
548 return false;
549 prev = key;
550 ++counted;
551 }
552
553 if (leaf->next != nullptr)
554 {
555 if (not leaf->next->leaf or leaf->next->keys.is_empty())
556 return false;
557 if (not cmp_(leaf->keys.get_last(), leaf->next->keys.get_first()))
558 return false;
559 }
560
561 leaf = leaf->next;
562 }
563
564 return counted == size_;
565 }
566
567 [[nodiscard]] bool verify_node(const Node *node, const std::optional<Key> &min_key, const std::optional<Key> &max_key,
568 const size_t depth, size_t &leaf_depth, size_t &counted) const
569 {
570 if (node == nullptr)
571 return false;
572
573 if (node != root_.get())
574 {
575 if (node->keys.size() < MinKeys or node->keys.size() > MaxKeys)
576 return false;
577 }
578 else if (node->keys.size() > MaxKeys)
579 return false;
580
581 if (not strictly_sorted(node->keys))
582 return false;
583
584 if (node->leaf)
585 {
586 if (min_key.has_value() and not node->keys.is_empty() and cmp_(node->keys.get_first(), *min_key))
587 return false;
588
589 if (max_key.has_value() and not node->keys.is_empty() and not cmp_(node->keys.get_last(), *max_key))
590 return false;
591
592 counted += node->keys.size();
593
594 if (leaf_depth == static_cast<size_t>(-1))
595 leaf_depth = depth;
596 return leaf_depth == depth;
597 }
598
599 if (node->children.size() != node->keys.size() + 1 or node->children.is_empty())
600 return false;
601
602 for (size_t i = 1; i < node->children.size(); ++i)
603 {
604 const Key *expected = subtree_min_ptr(node->children[i].get());
605 if (expected == nullptr or not equals(node->keys[i - 1], *expected))
606 return false;
607 }
608
609 for (size_t i = 0; i < node->children.size(); ++i)
610 {
611 std::optional<Key> child_min = min_key;
612 std::optional<Key> child_max = max_key;
613 if (i > 0)
614 child_min = node->keys[i - 1];
615 if (i < node->keys.size())
616 child_max = node->keys[i];
617
618 if (not verify_node(node->children[i].get(), child_min, child_max, depth + 1, leaf_depth, counted))
619 return false;
620 }
621
622 const Key *first = subtree_min_ptr(node->children.get_first().get());
623 const Key *last = subtree_max_ptr(node->children.get_last().get());
624 if (first == nullptr or last == nullptr)
625 return false;
626
627 if (min_key.has_value() and cmp_(*first, *min_key))
628 return false;
629
630 if (max_key.has_value() and not cmp_(*last, *max_key))
631 return false;
632
633 return true;
634 }
635
636public:
637 using key_type = Key;
638
646 {
647 const Gen_BPlus_Tree *tree_ = nullptr;
648 const Node *leaf_ = nullptr;
649 size_t idx_ = 0;
650 std::optional<Key> last_;
651
653 {
654 while (tree_ != nullptr and leaf_ != nullptr)
655 {
656 if (idx_ >= leaf_->keys.size())
657 {
658 leaf_ = leaf_->next;
659 idx_ = 0;
660 continue;
661 }
662
663 if (last_.has_value() and tree_->cmp_(*last_, leaf_->keys[idx_]))
664 {
665 leaf_ = nullptr;
666 idx_ = 0;
667 }
668 return;
669 }
670 }
671
672 public:
676 Iterator() noexcept = default;
677
682 explicit Iterator(const Gen_BPlus_Tree &tree) noexcept
683 : tree_(&tree), leaf_(tree.leftmost_leaf(tree.root_.get())), idx_(0)
684 {
686 }
687
695 Iterator(const Gen_BPlus_Tree &tree, const Key &first, const Key &last)
696 : tree_(&tree), leaf_(nullptr), idx_(0), last_(last)
697 {
698 ah_invalid_argument_if(tree.cmp_(last, first))
699 << "BPlus_Tree::Iterator(): invalid range (last < first)";
700
701 leaf_ = tree.find_leaf(first);
702 if (leaf_ != nullptr)
703 idx_ = tree.lower_bound_index(leaf_->keys, first);
705 }
706
711 [[nodiscard]] bool has_curr() const noexcept
712 {
713 return tree_ != nullptr and leaf_ != nullptr;
714 }
715
720 [[nodiscard]] const Key &get_curr() const
721 {
722 ah_underflow_error_if(not has_curr()) << "BPlus_Tree::Iterator::get_curr(): no current key";
723 return leaf_->keys[idx_];
724 }
725
730 void next_ne()
731 {
732 ah_underflow_error_if(not has_curr()) << "BPlus_Tree::Iterator::next_ne(): no current key";
733 ++idx_;
735 }
736
741 void next()
742 {
743 next_ne();
744 }
745
750 [[nodiscard]] const Key &operator*() const
751 {
752 return get_curr();
753 }
754
759 [[nodiscard]] const Key *operator->() const
760 {
761 return &get_curr();
762 }
763 };
764
769 explicit Gen_BPlus_Tree(const Compare &cmp = Compare()) : cmp_(cmp) {}
770
777 template <std::input_iterator It> Gen_BPlus_Tree(It first, It last, const Compare &cmp = Compare()) : cmp_(cmp)
778 {
779 insert_range(first, last);
780 }
781
787 Gen_BPlus_Tree(std::initializer_list<Key> init, const Compare &cmp = Compare())
788 : Gen_BPlus_Tree(init.begin(), init.end(), cmp)
789 {}
790
795 Gen_BPlus_Tree(const Gen_BPlus_Tree &other) : size_(other.size_), cmp_(other.cmp_)
796 {
797 Node *prev_leaf = nullptr;
798 root_ = clone_node(other.root_.get(), prev_leaf);
799 }
800
811 Gen_BPlus_Tree(Gen_BPlus_Tree &&other) noexcept(std::is_nothrow_copy_constructible_v<Compare>)
812 : root_(std::move(other.root_)), size_(std::exchange(other.size_, 0)), cmp_(other.cmp_)
813 {}
814
820 {
821 if (this == &other)
822 return *this;
823
824 // Copy-and-swap: build a complete copy first so that if cmp_'s
825 // copy-assignment (or clone_node) throws, *this is left unchanged.
826 Gen_BPlus_Tree tmp(other);
827 std::swap(root_, tmp.root_);
828 std::swap(size_, tmp.size_);
829 std::swap(cmp_, tmp.cmp_);
830 return *this;
831 }
832
838 Gen_BPlus_Tree &operator=(Gen_BPlus_Tree &&other) noexcept(noexcept(swap(other)))
839 {
840 swap(other);
841 return *this;
842 }
843
852 void swap(Gen_BPlus_Tree &other) noexcept(std::is_nothrow_swappable_v<Compare>)
853 {
854 // the swap that the specification evaluates: that of Compare found by
855 // its arguments, else std::swap(); first, since it may throw
856 using std::swap;
857 swap(cmp_, other.cmp_);
858 root_.swap(other.root_);
859 std::swap(size_, other.size_);
860 }
861
867 [[nodiscard]] const Compare &key_comp() const noexcept
868 {
869 return cmp_;
870 }
871
877 [[nodiscard]] const Compare &get_compare() const noexcept
878 {
879 return key_comp();
880 }
881
886 [[nodiscard]] bool empty() const noexcept
887 {
888 return size_ == 0;
889 }
890
895 [[nodiscard]] bool is_empty() const noexcept
896 {
897 return empty();
898 }
899
904 [[nodiscard]] size_t size() const noexcept
905 {
906 return size_;
907 }
908
913 [[nodiscard]] size_t height() const noexcept
914 {
915 return height_of(root_.get());
916 }
917
921 void clear() noexcept
922 {
923 root_.reset();
924 size_ = 0;
925 }
926
932 [[nodiscard]] bool contains(const Key &key) const
933 {
934 return contains_in(root_.get(), key);
935 }
936
942 [[nodiscard]] bool search(const Key &key) const
943 {
944 return contains(key);
945 }
946
954 bool insert(const Key &key)
955 {
956 if (contains(key))
957 return false;
958
959 if (root_ == nullptr)
960 {
961 auto leaf = std::make_unique<Node>(true);
962 leaf->keys.append(key);
963 root_ = std::move(leaf);
964 size_ = 1;
965 return true;
966 }
967
968 if (root_->keys.size() == MaxKeys)
969 {
970 auto new_root = std::make_unique<Node>(false);
971 new_root->children.append(std::move(root_));
972 try
973 {
974 split_child(new_root.get(), 0);
975 }
976 catch (...) // split_child() left the old root as it was
977 {
978 root_ = std::move(new_root->children(0));
979 throw;
980 }
981 root_ = std::move(new_root);
982 }
983
984 insert_nonfull(root_.get(), key);
985 ++size_;
986 return true;
987 }
988
996 bool insert(Key &&key)
997 {
998 Key copy = std::move(key);
999 return insert(copy);
1000 }
1001
1007 bool remove(const Key &key)
1008 {
1009 if (root_ == nullptr)
1010 return false;
1011
1012 const bool removed = remove_from(root_.get(), key);
1013 if (not removed)
1014 return false;
1015
1016 --size_;
1017
1018 if (root_->leaf and root_->keys.is_empty())
1019 root_.reset();
1020 else if (not root_->leaf and root_->children.size() == 1)
1021 root_ = std::move(root_->children.get_first());
1022
1023 return true;
1024 }
1025
1030 [[nodiscard]] std::optional<Key> min_key() const
1031 {
1032 const Key *ptr = subtree_min_ptr(root_.get());
1033 if (ptr == nullptr)
1034 return std::nullopt;
1035 return *ptr;
1036 }
1037
1042 [[nodiscard]] std::optional<Key> max_key() const
1043 {
1044 const Key *ptr = subtree_max_ptr(root_.get());
1045 if (ptr == nullptr)
1046 return std::nullopt;
1047 return *ptr;
1048 }
1049
1055 [[nodiscard]] std::optional<Key> lower_bound(const Key &key) const
1056 {
1057 const Node *leaf = find_leaf(key);
1058 if (leaf == nullptr)
1059 return std::nullopt;
1060
1061 size_t idx = lower_bound_index(leaf->keys, key);
1062 while (leaf != nullptr)
1063 {
1064 if (idx < leaf->keys.size())
1065 return leaf->keys[idx];
1066 leaf = leaf->next;
1067 idx = 0;
1068 }
1069
1070 return std::nullopt;
1071 }
1072
1078 [[nodiscard]] std::optional<Key> upper_bound(const Key &key) const
1079 {
1080 const Node *leaf = find_leaf(key);
1081 if (leaf == nullptr)
1082 return std::nullopt;
1083
1084 size_t idx = upper_bound_index(leaf->keys, key);
1085 while (leaf != nullptr)
1086 {
1087 if (idx < leaf->keys.size())
1088 return leaf->keys[idx];
1089 leaf = leaf->next;
1090 idx = 0;
1091 }
1092
1093 return std::nullopt;
1094 }
1095
1100 [[nodiscard]] Iterator get_it() const noexcept
1101 {
1102 return Iterator(*this);
1103 }
1104
1112 [[nodiscard]] Iterator get_range_it(const Key &first, const Key &last) const
1113 {
1114 return Iterator(*this, first, last);
1115 }
1116
1125 [[nodiscard]] Array<Key> range(const Key &first, const Key &last) const
1126 {
1128 out.reserve(8);
1129 for (auto it = get_range_it(first, last); it.has_curr(); it.next_ne())
1130 out.append(it.get_curr());
1131
1132 return out;
1133 }
1134
1140 [[nodiscard]] Array<Key> keys() const
1141 {
1143 out.reserve(size_ == 0 ? 1 : size_);
1144 for (auto it = get_it(); it.has_curr(); it.next_ne())
1145 out.append(it.get_curr());
1146
1147 return out;
1148 }
1149
1154 [[nodiscard]] bool verify() const
1155 {
1156 if (root_ == nullptr)
1157 return size_ == 0;
1158
1159 if (root_->keys.is_empty())
1160 return false;
1161
1162 auto leaf_depth = static_cast<size_t>(-1);
1163 size_t counted = 0;
1164 return verify_node(root_.get(), std::nullopt, std::nullopt, 1, leaf_depth, counted) and counted == size_
1166 }
1167};
1168
1174template <typename Key, class Compare = Aleph::less<Key>, size_t MinDegree = 16>
1176} // namespace Aleph
1177
1178#endif // TPL_BPLUS_TREE_H
C++20 concepts hub: comparison, BST policy, and Aleph container concepts.
Exception handling system with formatted messages for Aleph-w.
#define ah_runtime_error_unless(C)
Throws std::runtime_error if condition does NOT hold.
Definition ah-errors.H:399
#define ah_underflow_error_if(C)
Throws std::underflow_error if condition holds.
Definition ah-errors.H:517
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
Standard functor implementations and comparison objects.
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
Simple dynamic array with automatic resizing and functional operations.
Definition tpl_array.H:141
constexpr size_t size() const noexcept
Return the number of elements stored in the stack.
Definition tpl_array.H:450
void empty() noexcept
Empties the container.
Definition tpl_array.H:426
constexpr bool is_empty() const noexcept
Checks if the container is empty.
Definition tpl_array.H:444
void swap(Array &s) noexcept
Swap this with s
Definition tpl_array.H:313
T & get_last()
Return a modifiable reference to the last element.
Definition tpl_array.H:483
T & append(const T &data)
Append a copy of data
Definition tpl_array.H:331
void reserve(size_t cap)
Reserves cap cells into the array.
Definition tpl_array.H:402
void putn(const size_t n)
Reserve n additional logical slots in the array without value-initializing them.
Definition tpl_array.H:392
T & get_first()
Return a modifiable reference to the first element.
Definition tpl_array.H:465
Lazy iterator over ordered leaf keys.
void next()
Synonym for next_ne().
const Key * operator->() const
Member-access shorthand for the current key.
const Gen_BPlus_Tree * tree_
void next_ne()
Advance to the next key.
bool has_curr() const noexcept
Return whether the iterator still points to a key.
Iterator(const Gen_BPlus_Tree &tree, const Key &first, const Key &last)
Construct an iterator over the inclusive range [first, last].
Iterator() noexcept=default
Construct an exhausted iterator.
const Key & operator*() const
Dereference the iterator.
const Key & get_curr() const
Return the current key.
Generic B+ Tree with configurable minimum degree.
Gen_BPlus_Tree & operator=(const Gen_BPlus_Tree &other)
Copy assignment.
const Key * subtree_max_ptr(const Node *node) const noexcept
const Node * rightmost_leaf(const Node *node) const noexcept
size_t upper_bound_index(const Array< Key > &keys, const Key &key) const
void merge_children(Node *parent, const size_t left_idx)
void fix_underflow(Node *parent, const size_t idx)
static T erase_at(Array< T > &array, const size_t idx)
std::optional< Key > lower_bound(const Key &key) const
Return the first key not less than key.
bool verify_leaf_chain() const
Gen_BPlus_Tree(const Compare &cmp=Compare())
Construct an empty B+ Tree.
size_t height() const noexcept
Return the current tree height.
bool remove(const Key &key)
Remove a key if present.
bool search(const Key &key) const
Synonym for contains().
Array< Key > keys() const
Materialize the tree contents in sorted order.
size_t lower_bound_index(const Array< Key > &keys, const Key &key) const
bool empty() const noexcept
Return whether the tree has no keys.
void rebuild_separators(Node *node) const
static constexpr size_t MaxKeys
Gen_BPlus_Tree(It first, It last, const Compare &cmp=Compare())
Construct a B+ Tree from an iterator range.
std::unique_ptr< Node > root_
std::optional< Key > max_key() const
Return the maximum key, if any.
void swap(Gen_BPlus_Tree &other) noexcept(std::is_nothrow_swappable_v< Compare >)
Exchange the keys and the comparators of this tree and another.
bool verify() const
Verify structural B+ Tree invariants.
Gen_BPlus_Tree & operator=(Gen_BPlus_Tree &&other) noexcept(noexcept(swap(other)))
Move assignment: exchange this tree with another, which is left with the previous keys of this one.
static void append_move_range(Array< T > &dst, Array< T > &src, const size_t from)
bool insert(const Key &key)
Insert a key if it is not already present.
Gen_BPlus_Tree(const Gen_BPlus_Tree &other)
Copy constructor performing a deep copy.
void insert_nonfull(Node *node, const Key &key)
void split_child(Node *parent, const size_t idx)
const Compare & get_compare() const noexcept
Return the comparison object (read-only).
bool remove_from(Node *node, const Key &key)
Gen_BPlus_Tree(std::initializer_list< Key > init, const Compare &cmp=Compare())
Construct a B+ Tree from an initializer list.
const Key * subtree_min_ptr(const Node *node) const noexcept
static void append_copy_range(Array< T > &dst, const Array< T > &src, const size_t from)
std::optional< Key > min_key() const
Return the minimum key, if any.
void clear() noexcept
Remove every key from the tree.
Key key_type
Stored key type.
const Key & subtree_min(const Node *node) const
bool contains_in(const Node *node, const Key &key) const
const Compare & key_comp() const noexcept
Return the comparison object (read-only).
const Node * find_leaf(const Key &key) const
bool is_empty() const noexcept
Synonym for empty() in traditional Aleph style.
size_t height_of(const Node *node) const noexcept
void borrow_from_next(Node *parent, const size_t idx)
static void truncate(Array< T > &array, const size_t new_size)
std::optional< Key > upper_bound(const Key &key) const
Return the first key strictly greater than key.
size_t size() const noexcept
Return the number of stored keys.
Iterator get_it() const noexcept
Return a lazy iterator over the full key order.
bool verify_node(const Node *node, const std::optional< Key > &min_key, const std::optional< Key > &max_key, const size_t depth, size_t &leaf_depth, size_t &counted) const
bool strictly_sorted(const Array< Key > &keys) const
Gen_BPlus_Tree(Gen_BPlus_Tree &&other) noexcept(std::is_nothrow_copy_constructible_v< Compare >)
Move constructor: take the keys of another tree, which is left empty.
static constexpr size_t MinKeys
bool insert(Key &&key)
Insert a key by move if it is not already present.
bool contains(const Key &key) const
Return whether a key is present.
Iterator get_range_it(const Key &first, const Key &last) const
Return a lazy iterator over an inclusive key range.
static void insert_at(Array< T > &array, const size_t idx, U &&value)
const Node * leftmost_leaf(const Node *node) const noexcept
std::unique_ptr< Node > clone_node(const Node *node, Node *&prev_leaf) const
void insert_range(It first, It last)
size_t child_index(const Node *node, const Key &key) const
Array< Key > range(const Key &first, const Key &last) const
Collect all keys in the inclusive range [first, last].
bool equals(const Key &lhs, const Key &rhs) const
void borrow_from_prev(Node *parent, const size_t idx)
Minimal std::expected-style result type for C++20.
int cmp(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4196
bool bplus_equiv(const Compare &cmp, const Key &lhs, const Key &rhs)
Main namespace for Aleph-w library functions.
Itor2 copy(Itor1 sourceBeg, const Itor1 &sourceEnd, Itor2 destBeg)
Copy elements from one range to another.
Definition ahAlgo.H:584
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
void open_gap(Tarray &ptr, size_t n, size_t pos=0, size_t num_entries=1)
Open a gap in an array by shifting elements right.
Definition array_utils.H:96
static bool is_leaf(BinNode< std::string > *p) noexcept
Definition Huffman.H:109
static std::atomic< bool > init
Definition hash-fct.C:54
void close_gap(T *ptr, size_t n, size_t pos, size_t num_entries=1)
Close a gap in an array by shifting elements left.
STL namespace.
BPlusTreeNode(const bool is_leaf)
Array< std::unique_ptr< BPlusTreeNode > > children
Aleph::DynList< T > keys() const
See items().
Definition ah-dry.H:2916
Dynamic array container with automatic resizing.
Comprehensive sorting algorithms and search utilities for Aleph-w.