1 // Copyright 2018 The Abseil Authors.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 // A btree implementation of the STL set and map interfaces. A btree is smaller
16 // and generally also faster than STL set/map (refer to the benchmarks below).
17 // The red-black tree implementation of STL set/map has an overhead of 3
18 // pointers (left, right and parent) plus the node color information for each
19 // stored value. So a set<int32_t> consumes 40 bytes for each value stored in
20 // 64-bit mode. This btree implementation stores multiple values on fixed
21 // size nodes (usually 256 bytes) and doesn't store child pointers for leaf
22 // nodes. The result is that a btree_set<int32_t> may use much less memory per
23 // stored value. For the random insertion benchmark in btree_bench.cc, a
24 // btree_set<int32_t> with node-size of 256 uses 5.1 bytes per stored value.
25 //
26 // The packing of multiple values on to each node of a btree has another effect
27 // besides better space utilization: better cache locality due to fewer cache
28 // lines being accessed. Better cache locality translates into faster
29 // operations.
30 //
31 // CAVEATS
32 //
33 // Insertions and deletions on a btree can cause splitting, merging or
34 // rebalancing of btree nodes. And even without these operations, insertions
35 // and deletions on a btree will move values around within a node. In both
36 // cases, the result is that insertions and deletions can invalidate iterators
37 // pointing to values other than the one being inserted/deleted. Therefore, this
38 // container does not provide pointer stability. This is notably different from
39 // STL set/map which takes care to not invalidate iterators on insert/erase
40 // except, of course, for iterators pointing to the value being erased. A
41 // partial workaround when erasing is available: erase() returns an iterator
42 // pointing to the item just after the one that was erased (or end() if none
43 // exists).
44
45 #ifndef ABSL_CONTAINER_INTERNAL_BTREE_H_
46 #define ABSL_CONTAINER_INTERNAL_BTREE_H_
47
48 #include <algorithm>
49 #include <cassert>
50 #include <cstddef>
51 #include <cstdint>
52 #include <cstring>
53 #include <functional>
54 #include <iterator>
55 #include <limits>
56 #include <new>
57 #include <string>
58 #include <type_traits>
59 #include <utility>
60
61 #include "absl/base/internal/raw_logging.h"
62 #include "absl/base/macros.h"
63 #include "absl/container/internal/common.h"
64 #include "absl/container/internal/common_policy_traits.h"
65 #include "absl/container/internal/compressed_tuple.h"
66 #include "absl/container/internal/container_memory.h"
67 #include "absl/container/internal/layout.h"
68 #include "absl/memory/memory.h"
69 #include "absl/meta/type_traits.h"
70 #include "absl/strings/cord.h"
71 #include "absl/strings/string_view.h"
72 #include "absl/types/compare.h"
73 #include "absl/utility/utility.h"
74
75 namespace absl {
76 ABSL_NAMESPACE_BEGIN
77 namespace container_internal {
78
79 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
80 #error ABSL_BTREE_ENABLE_GENERATIONS cannot be directly set
81 #elif defined(ABSL_HAVE_ADDRESS_SANITIZER) || \
82 defined(ABSL_HAVE_MEMORY_SANITIZER)
83 // When compiled in sanitizer mode, we add generation integers to the nodes and
84 // iterators. When iterators are used, we validate that the container has not
85 // been mutated since the iterator was constructed.
86 #define ABSL_BTREE_ENABLE_GENERATIONS
87 #endif
88
89 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
BtreeGenerationsEnabled()90 constexpr bool BtreeGenerationsEnabled() { return true; }
91 #else
92 constexpr bool BtreeGenerationsEnabled() { return false; }
93 #endif
94
95 template <typename Compare, typename T, typename U>
96 using compare_result_t = absl::result_of_t<const Compare(const T &, const U &)>;
97
98 // A helper class that indicates if the Compare parameter is a key-compare-to
99 // comparator.
100 template <typename Compare, typename T>
101 using btree_is_key_compare_to =
102 std::is_convertible<compare_result_t<Compare, T, T>, absl::weak_ordering>;
103
104 struct StringBtreeDefaultLess {
105 using is_transparent = void;
106
107 StringBtreeDefaultLess() = default;
108
109 // Compatibility constructor.
StringBtreeDefaultLessStringBtreeDefaultLess110 StringBtreeDefaultLess(std::less<std::string>) {} // NOLINT
StringBtreeDefaultLessStringBtreeDefaultLess111 StringBtreeDefaultLess(std::less<absl::string_view>) {} // NOLINT
112
113 // Allow converting to std::less for use in key_comp()/value_comp().
114 explicit operator std::less<std::string>() const { return {}; }
115 explicit operator std::less<absl::string_view>() const { return {}; }
116 explicit operator std::less<absl::Cord>() const { return {}; }
117
operatorStringBtreeDefaultLess118 absl::weak_ordering operator()(absl::string_view lhs,
119 absl::string_view rhs) const {
120 return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
121 }
StringBtreeDefaultLessStringBtreeDefaultLess122 StringBtreeDefaultLess(std::less<absl::Cord>) {} // NOLINT
operatorStringBtreeDefaultLess123 absl::weak_ordering operator()(const absl::Cord &lhs,
124 const absl::Cord &rhs) const {
125 return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
126 }
operatorStringBtreeDefaultLess127 absl::weak_ordering operator()(const absl::Cord &lhs,
128 absl::string_view rhs) const {
129 return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
130 }
operatorStringBtreeDefaultLess131 absl::weak_ordering operator()(absl::string_view lhs,
132 const absl::Cord &rhs) const {
133 return compare_internal::compare_result_as_ordering(-rhs.Compare(lhs));
134 }
135 };
136
137 struct StringBtreeDefaultGreater {
138 using is_transparent = void;
139
140 StringBtreeDefaultGreater() = default;
141
StringBtreeDefaultGreaterStringBtreeDefaultGreater142 StringBtreeDefaultGreater(std::greater<std::string>) {} // NOLINT
StringBtreeDefaultGreaterStringBtreeDefaultGreater143 StringBtreeDefaultGreater(std::greater<absl::string_view>) {} // NOLINT
144
145 // Allow converting to std::greater for use in key_comp()/value_comp().
146 explicit operator std::greater<std::string>() const { return {}; }
147 explicit operator std::greater<absl::string_view>() const { return {}; }
148 explicit operator std::greater<absl::Cord>() const { return {}; }
149
operatorStringBtreeDefaultGreater150 absl::weak_ordering operator()(absl::string_view lhs,
151 absl::string_view rhs) const {
152 return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
153 }
StringBtreeDefaultGreaterStringBtreeDefaultGreater154 StringBtreeDefaultGreater(std::greater<absl::Cord>) {} // NOLINT
operatorStringBtreeDefaultGreater155 absl::weak_ordering operator()(const absl::Cord &lhs,
156 const absl::Cord &rhs) const {
157 return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
158 }
operatorStringBtreeDefaultGreater159 absl::weak_ordering operator()(const absl::Cord &lhs,
160 absl::string_view rhs) const {
161 return compare_internal::compare_result_as_ordering(-lhs.Compare(rhs));
162 }
operatorStringBtreeDefaultGreater163 absl::weak_ordering operator()(absl::string_view lhs,
164 const absl::Cord &rhs) const {
165 return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
166 }
167 };
168
169 // See below comments for checked_compare.
170 template <typename Compare, bool is_class = std::is_class<Compare>::value>
171 struct checked_compare_base : Compare {
172 using Compare::Compare;
checked_compare_basechecked_compare_base173 explicit checked_compare_base(Compare c) : Compare(std::move(c)) {}
compchecked_compare_base174 const Compare &comp() const { return *this; }
175 };
176 template <typename Compare>
177 struct checked_compare_base<Compare, false> {
178 explicit checked_compare_base(Compare c) : compare(std::move(c)) {}
179 const Compare &comp() const { return compare; }
180 Compare compare;
181 };
182
183 // A mechanism for opting out of checked_compare for use only in btree_test.cc.
184 struct BtreeTestOnlyCheckedCompareOptOutBase {};
185
186 // A helper class to adapt the specified comparator for two use cases:
187 // (1) When using common Abseil string types with common comparison functors,
188 // convert a boolean comparison into a three-way comparison that returns an
189 // `absl::weak_ordering`. This helper class is specialized for
190 // less<std::string>, greater<std::string>, less<string_view>,
191 // greater<string_view>, less<absl::Cord>, and greater<absl::Cord>.
192 // (2) Adapt the comparator to diagnose cases of non-strict-weak-ordering (see
193 // https://en.cppreference.com/w/cpp/named_req/Compare) in debug mode. Whenever
194 // a comparison is made, we will make assertions to verify that the comparator
195 // is valid.
196 template <typename Compare, typename Key>
197 struct key_compare_adapter {
198 // Inherit from checked_compare_base to support function pointers and also
199 // keep empty-base-optimization (EBO) support for classes.
200 // Note: we can't use CompressedTuple here because that would interfere
201 // with the EBO for `btree::rightmost_`. `btree::rightmost_` is itself a
202 // CompressedTuple and nested `CompressedTuple`s don't support EBO.
203 // TODO(b/214288561): use CompressedTuple instead once it supports EBO for
204 // nested `CompressedTuple`s.
205 struct checked_compare : checked_compare_base<Compare> {
206 private:
207 using Base = typename checked_compare::checked_compare_base;
208 using Base::comp;
209
210 // If possible, returns whether `t` is equivalent to itself. We can only do
211 // this for `Key`s because we can't be sure that it's safe to call
212 // `comp()(k, k)` otherwise. Even if SFINAE allows it, there could be a
213 // compilation failure inside the implementation of the comparison operator.
214 bool is_self_equivalent(const Key &k) const {
215 // Note: this works for both boolean and three-way comparators.
216 return comp()(k, k) == 0;
217 }
218 // If we can't compare `t` with itself, returns true unconditionally.
219 template <typename T>
220 bool is_self_equivalent(const T &) const {
221 return true;
222 }
223
224 public:
225 using Base::Base;
226 checked_compare(Compare comp) : Base(std::move(comp)) {} // NOLINT
227
228 // Allow converting to Compare for use in key_comp()/value_comp().
229 explicit operator Compare() const { return comp(); }
230
231 template <typename T, typename U,
232 absl::enable_if_t<
233 std::is_same<bool, compare_result_t<Compare, T, U>>::value,
234 int> = 0>
235 bool operator()(const T &lhs, const U &rhs) const {
236 // NOTE: if any of these assertions fail, then the comparator does not
237 // establish a strict-weak-ordering (see
238 // https://en.cppreference.com/w/cpp/named_req/Compare).
239 assert(is_self_equivalent(lhs));
240 assert(is_self_equivalent(rhs));
241 const bool lhs_comp_rhs = comp()(lhs, rhs);
242 assert(!lhs_comp_rhs || !comp()(rhs, lhs));
243 return lhs_comp_rhs;
244 }
245
246 template <
247 typename T, typename U,
248 absl::enable_if_t<std::is_convertible<compare_result_t<Compare, T, U>,
249 absl::weak_ordering>::value,
250 int> = 0>
251 absl::weak_ordering operator()(const T &lhs, const U &rhs) const {
252 // NOTE: if any of these assertions fail, then the comparator does not
253 // establish a strict-weak-ordering (see
254 // https://en.cppreference.com/w/cpp/named_req/Compare).
255 assert(is_self_equivalent(lhs));
256 assert(is_self_equivalent(rhs));
257 const absl::weak_ordering lhs_comp_rhs = comp()(lhs, rhs);
258 #ifndef NDEBUG
259 const absl::weak_ordering rhs_comp_lhs = comp()(rhs, lhs);
260 if (lhs_comp_rhs > 0) {
261 assert(rhs_comp_lhs < 0 && "lhs_comp_rhs > 0 -> rhs_comp_lhs < 0");
262 } else if (lhs_comp_rhs == 0) {
263 assert(rhs_comp_lhs == 0 && "lhs_comp_rhs == 0 -> rhs_comp_lhs == 0");
264 } else {
265 assert(rhs_comp_lhs > 0 && "lhs_comp_rhs < 0 -> rhs_comp_lhs > 0");
266 }
267 #endif
268 return lhs_comp_rhs;
269 }
270 };
271 using type = absl::conditional_t<
272 std::is_base_of<BtreeTestOnlyCheckedCompareOptOutBase, Compare>::value,
273 Compare, checked_compare>;
274 };
275
276 template <>
277 struct key_compare_adapter<std::less<std::string>, std::string> {
278 using type = StringBtreeDefaultLess;
279 };
280
281 template <>
282 struct key_compare_adapter<std::greater<std::string>, std::string> {
283 using type = StringBtreeDefaultGreater;
284 };
285
286 template <>
287 struct key_compare_adapter<std::less<absl::string_view>, absl::string_view> {
288 using type = StringBtreeDefaultLess;
289 };
290
291 template <>
292 struct key_compare_adapter<std::greater<absl::string_view>, absl::string_view> {
293 using type = StringBtreeDefaultGreater;
294 };
295
296 template <>
297 struct key_compare_adapter<std::less<absl::Cord>, absl::Cord> {
298 using type = StringBtreeDefaultLess;
299 };
300
301 template <>
302 struct key_compare_adapter<std::greater<absl::Cord>, absl::Cord> {
303 using type = StringBtreeDefaultGreater;
304 };
305
306 // Detects an 'absl_btree_prefer_linear_node_search' member. This is
307 // a protocol used as an opt-in or opt-out of linear search.
308 //
309 // For example, this would be useful for key types that wrap an integer
310 // and define their own cheap operator<(). For example:
311 //
312 // class K {
313 // public:
314 // using absl_btree_prefer_linear_node_search = std::true_type;
315 // ...
316 // private:
317 // friend bool operator<(K a, K b) { return a.k_ < b.k_; }
318 // int k_;
319 // };
320 //
321 // btree_map<K, V> m; // Uses linear search
322 //
323 // If T has the preference tag, then it has a preference.
324 // Btree will use the tag's truth value.
325 template <typename T, typename = void>
326 struct has_linear_node_search_preference : std::false_type {};
327 template <typename T, typename = void>
328 struct prefers_linear_node_search : std::false_type {};
329 template <typename T>
330 struct has_linear_node_search_preference<
331 T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
332 : std::true_type {};
333 template <typename T>
334 struct prefers_linear_node_search<
335 T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
336 : T::absl_btree_prefer_linear_node_search {};
337
338 template <typename Compare, typename Key>
339 constexpr bool compare_has_valid_result_type() {
340 using compare_result_type = compare_result_t<Compare, Key, Key>;
341 return std::is_same<compare_result_type, bool>::value ||
342 std::is_convertible<compare_result_type, absl::weak_ordering>::value;
343 }
344
345 template <typename original_key_compare, typename value_type>
346 class map_value_compare {
347 template <typename Params>
348 friend class btree;
349
350 // Note: this `protected` is part of the API of std::map::value_compare. See
351 // https://en.cppreference.com/w/cpp/container/map/value_compare.
352 protected:
353 explicit map_value_compare(original_key_compare c) : comp(std::move(c)) {}
354
355 original_key_compare comp; // NOLINT
356
357 public:
358 auto operator()(const value_type &lhs, const value_type &rhs) const
359 -> decltype(comp(lhs.first, rhs.first)) {
360 return comp(lhs.first, rhs.first);
361 }
362 };
363
364 template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
365 bool IsMulti, bool IsMap, typename SlotPolicy>
366 struct common_params : common_policy_traits<SlotPolicy> {
367 using original_key_compare = Compare;
368
369 // If Compare is a common comparator for a string-like type, then we adapt it
370 // to use heterogeneous lookup and to be a key-compare-to comparator.
371 // We also adapt the comparator to diagnose invalid comparators in debug mode.
372 // We disable this when `Compare` is invalid in a way that will cause
373 // adaptation to fail (having invalid return type) so that we can give a
374 // better compilation failure in static_assert_validation. If we don't do
375 // this, then there will be cascading compilation failures that are confusing
376 // for users.
377 using key_compare =
378 absl::conditional_t<!compare_has_valid_result_type<Compare, Key>(),
379 Compare,
380 typename key_compare_adapter<Compare, Key>::type>;
381
382 static constexpr bool kIsKeyCompareStringAdapted =
383 std::is_same<key_compare, StringBtreeDefaultLess>::value ||
384 std::is_same<key_compare, StringBtreeDefaultGreater>::value;
385 static constexpr bool kIsKeyCompareTransparent =
386 IsTransparent<original_key_compare>::value || kIsKeyCompareStringAdapted;
387
388 // A type which indicates if we have a key-compare-to functor or a plain old
389 // key-compare functor.
390 using is_key_compare_to = btree_is_key_compare_to<key_compare, Key>;
391
392 using allocator_type = Alloc;
393 using key_type = Key;
394 using size_type = size_t;
395 using difference_type = ptrdiff_t;
396
397 using slot_policy = SlotPolicy;
398 using slot_type = typename slot_policy::slot_type;
399 using value_type = typename slot_policy::value_type;
400 using init_type = typename slot_policy::mutable_value_type;
401 using pointer = value_type *;
402 using const_pointer = const value_type *;
403 using reference = value_type &;
404 using const_reference = const value_type &;
405
406 using value_compare =
407 absl::conditional_t<IsMap,
408 map_value_compare<original_key_compare, value_type>,
409 original_key_compare>;
410 using is_map_container = std::integral_constant<bool, IsMap>;
411
412 // For the given lookup key type, returns whether we can have multiple
413 // equivalent keys in the btree. If this is a multi-container, then we can.
414 // Otherwise, we can have multiple equivalent keys only if all of the
415 // following conditions are met:
416 // - The comparator is transparent.
417 // - The lookup key type is not the same as key_type.
418 // - The comparator is not a StringBtreeDefault{Less,Greater} comparator
419 // that we know has the same equivalence classes for all lookup types.
420 template <typename LookupKey>
421 constexpr static bool can_have_multiple_equivalent_keys() {
422 return IsMulti || (IsTransparent<key_compare>::value &&
423 !std::is_same<LookupKey, Key>::value &&
424 !kIsKeyCompareStringAdapted);
425 }
426
427 enum {
428 kTargetNodeSize = TargetNodeSize,
429
430 // Upper bound for the available space for slots. This is largest for leaf
431 // nodes, which have overhead of at least a pointer + 4 bytes (for storing
432 // 3 field_types and an enum).
433 kNodeSlotSpace = TargetNodeSize - /*minimum overhead=*/(sizeof(void *) + 4),
434 };
435
436 // This is an integral type large enough to hold as many slots as will fit a
437 // node of TargetNodeSize bytes.
438 using node_count_type =
439 absl::conditional_t<(kNodeSlotSpace / sizeof(slot_type) >
440 (std::numeric_limits<uint8_t>::max)()),
441 uint16_t, uint8_t>; // NOLINT
442 };
443
444 // An adapter class that converts a lower-bound compare into an upper-bound
445 // compare. Note: there is no need to make a version of this adapter specialized
446 // for key-compare-to functors because the upper-bound (the first value greater
447 // than the input) is never an exact match.
448 template <typename Compare>
449 struct upper_bound_adapter {
450 explicit upper_bound_adapter(const Compare &c) : comp(c) {}
451 template <typename K1, typename K2>
452 bool operator()(const K1 &a, const K2 &b) const {
453 // Returns true when a is not greater than b.
454 return !compare_internal::compare_result_as_less_than(comp(b, a));
455 }
456
457 private:
458 Compare comp;
459 };
460
461 enum class MatchKind : uint8_t { kEq, kNe };
462
463 template <typename V, bool IsCompareTo>
464 struct SearchResult {
465 V value;
466 MatchKind match;
467
468 static constexpr bool HasMatch() { return true; }
469 bool IsEq() const { return match == MatchKind::kEq; }
470 };
471
472 // When we don't use CompareTo, `match` is not present.
473 // This ensures that callers can't use it accidentally when it provides no
474 // useful information.
475 template <typename V>
476 struct SearchResult<V, false> {
477 SearchResult() {}
478 explicit SearchResult(V v) : value(v) {}
479 SearchResult(V v, MatchKind /*match*/) : value(v) {}
480
481 V value;
482
483 static constexpr bool HasMatch() { return false; }
484 static constexpr bool IsEq() { return false; }
485 };
486
487 // A node in the btree holding. The same node type is used for both internal
488 // and leaf nodes in the btree, though the nodes are allocated in such a way
489 // that the children array is only valid in internal nodes.
490 template <typename Params>
491 class btree_node {
492 using is_key_compare_to = typename Params::is_key_compare_to;
493 using field_type = typename Params::node_count_type;
494 using allocator_type = typename Params::allocator_type;
495 using slot_type = typename Params::slot_type;
496 using original_key_compare = typename Params::original_key_compare;
497
498 public:
499 using params_type = Params;
500 using key_type = typename Params::key_type;
501 using value_type = typename Params::value_type;
502 using pointer = typename Params::pointer;
503 using const_pointer = typename Params::const_pointer;
504 using reference = typename Params::reference;
505 using const_reference = typename Params::const_reference;
506 using key_compare = typename Params::key_compare;
507 using size_type = typename Params::size_type;
508 using difference_type = typename Params::difference_type;
509
510 // Btree decides whether to use linear node search as follows:
511 // - If the comparator expresses a preference, use that.
512 // - If the key expresses a preference, use that.
513 // - If the key is arithmetic and the comparator is std::less or
514 // std::greater, choose linear.
515 // - Otherwise, choose binary.
516 // TODO(ezb): Might make sense to add condition(s) based on node-size.
517 using use_linear_search = std::integral_constant<
518 bool, has_linear_node_search_preference<original_key_compare>::value
519 ? prefers_linear_node_search<original_key_compare>::value
520 : has_linear_node_search_preference<key_type>::value
521 ? prefers_linear_node_search<key_type>::value
522 : std::is_arithmetic<key_type>::value &&
523 (std::is_same<std::less<key_type>,
524 original_key_compare>::value ||
525 std::is_same<std::greater<key_type>,
526 original_key_compare>::value)>;
527
528 // This class is organized by absl::container_internal::Layout as if it had
529 // the following structure:
530 // // A pointer to the node's parent.
531 // btree_node *parent;
532 //
533 // // When ABSL_BTREE_ENABLE_GENERATIONS is defined, we also have a
534 // // generation integer in order to check that when iterators are
535 // // used, they haven't been invalidated already. Only the generation on
536 // // the root is used, but we have one on each node because whether a node
537 // // is root or not can change.
538 // uint32_t generation;
539 //
540 // // The position of the node in the node's parent.
541 // field_type position;
542 // // The index of the first populated value in `values`.
543 // // TODO(ezb): right now, `start` is always 0. Update insertion/merge
544 // // logic to allow for floating storage within nodes.
545 // field_type start;
546 // // The index after the last populated value in `values`. Currently, this
547 // // is the same as the count of values.
548 // field_type finish;
549 // // The maximum number of values the node can hold. This is an integer in
550 // // [1, kNodeSlots] for root leaf nodes, kNodeSlots for non-root leaf
551 // // nodes, and kInternalNodeMaxCount (as a sentinel value) for internal
552 // // nodes (even though there are still kNodeSlots values in the node).
553 // // TODO(ezb): make max_count use only 4 bits and record log2(capacity)
554 // // to free extra bits for is_root, etc.
555 // field_type max_count;
556 //
557 // // The array of values. The capacity is `max_count` for leaf nodes and
558 // // kNodeSlots for internal nodes. Only the values in
559 // // [start, finish) have been initialized and are valid.
560 // slot_type values[max_count];
561 //
562 // // The array of child pointers. The keys in children[i] are all less
563 // // than key(i). The keys in children[i + 1] are all greater than key(i).
564 // // There are 0 children for leaf nodes and kNodeSlots + 1 children for
565 // // internal nodes.
566 // btree_node *children[kNodeSlots + 1];
567 //
568 // This class is only constructed by EmptyNodeType. Normally, pointers to the
569 // layout above are allocated, cast to btree_node*, and de-allocated within
570 // the btree implementation.
571 ~btree_node() = default;
572 btree_node(btree_node const &) = delete;
573 btree_node &operator=(btree_node const &) = delete;
574
575 // Public for EmptyNodeType.
576 constexpr static size_type Alignment() {
577 static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(),
578 "Alignment of all nodes must be equal.");
579 return InternalLayout().Alignment();
580 }
581
582 protected:
583 btree_node() = default;
584
585 private:
586 using layout_type =
587 absl::container_internal::Layout<btree_node *, uint32_t, field_type,
588 slot_type, btree_node *>;
589 constexpr static size_type SizeWithNSlots(size_type n) {
590 return layout_type(
591 /*parent*/ 1,
592 /*generation*/ BtreeGenerationsEnabled() ? 1 : 0,
593 /*position, start, finish, max_count*/ 4,
594 /*slots*/ n,
595 /*children*/ 0)
596 .AllocSize();
597 }
598 // A lower bound for the overhead of fields other than slots in a leaf node.
599 constexpr static size_type MinimumOverhead() {
600 return SizeWithNSlots(1) - sizeof(slot_type);
601 }
602
603 // Compute how many values we can fit onto a leaf node taking into account
604 // padding.
605 constexpr static size_type NodeTargetSlots(const size_type begin,
606 const size_type end) {
607 return begin == end ? begin
608 : SizeWithNSlots((begin + end) / 2 + 1) >
609 params_type::kTargetNodeSize
610 ? NodeTargetSlots(begin, (begin + end) / 2)
611 : NodeTargetSlots((begin + end) / 2 + 1, end);
612 }
613
614 constexpr static size_type kTargetNodeSize = params_type::kTargetNodeSize;
615 constexpr static size_type kNodeTargetSlots =
616 NodeTargetSlots(0, kTargetNodeSize);
617
618 // We need a minimum of 3 slots per internal node in order to perform
619 // splitting (1 value for the two nodes involved in the split and 1 value
620 // propagated to the parent as the delimiter for the split). For performance
621 // reasons, we don't allow 3 slots-per-node due to bad worst case occupancy of
622 // 1/3 (for a node, not a b-tree).
623 constexpr static size_type kMinNodeSlots = 4;
624
625 constexpr static size_type kNodeSlots =
626 kNodeTargetSlots >= kMinNodeSlots ? kNodeTargetSlots : kMinNodeSlots;
627
628 // The node is internal (i.e. is not a leaf node) if and only if `max_count`
629 // has this value.
630 constexpr static field_type kInternalNodeMaxCount = 0;
631
632 constexpr static layout_type Layout(const size_type slot_count,
633 const size_type child_count) {
634 return layout_type(
635 /*parent*/ 1,
636 /*generation*/ BtreeGenerationsEnabled() ? 1 : 0,
637 /*position, start, finish, max_count*/ 4,
638 /*slots*/ slot_count,
639 /*children*/ child_count);
640 }
641 // Leaves can have less than kNodeSlots values.
642 constexpr static layout_type LeafLayout(
643 const size_type slot_count = kNodeSlots) {
644 return Layout(slot_count, 0);
645 }
646 constexpr static layout_type InternalLayout() {
647 return Layout(kNodeSlots, kNodeSlots + 1);
648 }
649 constexpr static size_type LeafSize(const size_type slot_count = kNodeSlots) {
650 return LeafLayout(slot_count).AllocSize();
651 }
652 constexpr static size_type InternalSize() {
653 return InternalLayout().AllocSize();
654 }
655
656 // N is the index of the type in the Layout definition.
657 // ElementType<N> is the Nth type in the Layout definition.
658 template <size_type N>
659 inline typename layout_type::template ElementType<N> *GetField() {
660 // We assert that we don't read from values that aren't there.
661 assert(N < 4 || is_internal());
662 return InternalLayout().template Pointer<N>(reinterpret_cast<char *>(this));
663 }
664 template <size_type N>
665 inline const typename layout_type::template ElementType<N> *GetField() const {
666 assert(N < 4 || is_internal());
667 return InternalLayout().template Pointer<N>(
668 reinterpret_cast<const char *>(this));
669 }
670 void set_parent(btree_node *p) { *GetField<0>() = p; }
671 field_type &mutable_finish() { return GetField<2>()[2]; }
672 slot_type *slot(size_type i) { return &GetField<3>()[i]; }
673 slot_type *start_slot() { return slot(start()); }
674 slot_type *finish_slot() { return slot(finish()); }
675 const slot_type *slot(size_type i) const { return &GetField<3>()[i]; }
676 void set_position(field_type v) { GetField<2>()[0] = v; }
677 void set_start(field_type v) { GetField<2>()[1] = v; }
678 void set_finish(field_type v) { GetField<2>()[2] = v; }
679 // This method is only called by the node init methods.
680 void set_max_count(field_type v) { GetField<2>()[3] = v; }
681
682 public:
683 // Whether this is a leaf node or not. This value doesn't change after the
684 // node is created.
685 bool is_leaf() const { return GetField<2>()[3] != kInternalNodeMaxCount; }
686 // Whether this is an internal node or not. This value doesn't change after
687 // the node is created.
688 bool is_internal() const { return !is_leaf(); }
689
690 // Getter for the position of this node in its parent.
691 field_type position() const { return GetField<2>()[0]; }
692
693 // Getter for the offset of the first value in the `values` array.
694 field_type start() const {
695 // TODO(ezb): when floating storage is implemented, return GetField<2>()[1];
696 assert(GetField<2>()[1] == 0);
697 return 0;
698 }
699
700 // Getter for the offset after the last value in the `values` array.
701 field_type finish() const { return GetField<2>()[2]; }
702
703 // Getters for the number of values stored in this node.
704 field_type count() const {
705 assert(finish() >= start());
706 return finish() - start();
707 }
708 field_type max_count() const {
709 // Internal nodes have max_count==kInternalNodeMaxCount.
710 // Leaf nodes have max_count in [1, kNodeSlots].
711 const field_type max_count = GetField<2>()[3];
712 return max_count == field_type{kInternalNodeMaxCount}
713 ? field_type{kNodeSlots}
714 : max_count;
715 }
716
717 // Getter for the parent of this node.
718 btree_node *parent() const { return *GetField<0>(); }
719 // Getter for whether the node is the root of the tree. The parent of the
720 // root of the tree is the leftmost node in the tree which is guaranteed to
721 // be a leaf.
722 bool is_root() const { return parent()->is_leaf(); }
723 void make_root() {
724 assert(parent()->is_root());
725 set_generation(parent()->generation());
726 set_parent(parent()->parent());
727 }
728
729 // Gets the root node's generation integer, which is the one used by the tree.
730 uint32_t *get_root_generation() const {
731 assert(BtreeGenerationsEnabled());
732 const btree_node *curr = this;
733 for (; !curr->is_root(); curr = curr->parent()) continue;
734 return const_cast<uint32_t *>(&curr->GetField<1>()[0]);
735 }
736
737 // Returns the generation for iterator validation.
738 uint32_t generation() const {
739 return BtreeGenerationsEnabled() ? *get_root_generation() : 0;
740 }
741 // Updates generation. Should only be called on a root node or during node
742 // initialization.
743 void set_generation(uint32_t generation) {
744 if (BtreeGenerationsEnabled()) GetField<1>()[0] = generation;
745 }
746 // Updates the generation. We do this whenever the node is mutated.
747 void next_generation() {
748 if (BtreeGenerationsEnabled()) ++*get_root_generation();
749 }
750
751 // Getters for the key/value at position i in the node.
752 const key_type &key(size_type i) const { return params_type::key(slot(i)); }
753 reference value(size_type i) { return params_type::element(slot(i)); }
754 const_reference value(size_type i) const {
755 return params_type::element(slot(i));
756 }
757
758 // Getters/setter for the child at position i in the node.
759 btree_node *child(field_type i) const { return GetField<4>()[i]; }
760 btree_node *start_child() const { return child(start()); }
761 btree_node *&mutable_child(field_type i) { return GetField<4>()[i]; }
762 void clear_child(field_type i) {
763 absl::container_internal::SanitizerPoisonObject(&mutable_child(i));
764 }
765 void set_child_noupdate_position(field_type i, btree_node *c) {
766 absl::container_internal::SanitizerUnpoisonObject(&mutable_child(i));
767 mutable_child(i) = c;
768 }
769 void set_child(field_type i, btree_node *c) {
770 set_child_noupdate_position(i, c);
771 c->set_position(i);
772 }
773 void init_child(field_type i, btree_node *c) {
774 set_child(i, c);
775 c->set_parent(this);
776 }
777
778 // Returns the position of the first value whose key is not less than k.
779 template <typename K>
780 SearchResult<size_type, is_key_compare_to::value> lower_bound(
781 const K &k, const key_compare &comp) const {
782 return use_linear_search::value ? linear_search(k, comp)
783 : binary_search(k, comp);
784 }
785 // Returns the position of the first value whose key is greater than k.
786 template <typename K>
787 size_type upper_bound(const K &k, const key_compare &comp) const {
788 auto upper_compare = upper_bound_adapter<key_compare>(comp);
789 return use_linear_search::value ? linear_search(k, upper_compare).value
790 : binary_search(k, upper_compare).value;
791 }
792
793 template <typename K, typename Compare>
794 SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value>
795 linear_search(const K &k, const Compare &comp) const {
796 return linear_search_impl(k, start(), finish(), comp,
797 btree_is_key_compare_to<Compare, key_type>());
798 }
799
800 template <typename K, typename Compare>
801 SearchResult<size_type, btree_is_key_compare_to<Compare, key_type>::value>
802 binary_search(const K &k, const Compare &comp) const {
803 return binary_search_impl(k, start(), finish(), comp,
804 btree_is_key_compare_to<Compare, key_type>());
805 }
806
807 // Returns the position of the first value whose key is not less than k using
808 // linear search performed using plain compare.
809 template <typename K, typename Compare>
810 SearchResult<size_type, false> linear_search_impl(
811 const K &k, size_type s, const size_type e, const Compare &comp,
812 std::false_type /* IsCompareTo */) const {
813 while (s < e) {
814 if (!comp(key(s), k)) {
815 break;
816 }
817 ++s;
818 }
819 return SearchResult<size_type, false>{s};
820 }
821
822 // Returns the position of the first value whose key is not less than k using
823 // linear search performed using compare-to.
824 template <typename K, typename Compare>
825 SearchResult<size_type, true> linear_search_impl(
826 const K &k, size_type s, const size_type e, const Compare &comp,
827 std::true_type /* IsCompareTo */) const {
828 while (s < e) {
829 const absl::weak_ordering c = comp(key(s), k);
830 if (c == 0) {
831 return {s, MatchKind::kEq};
832 } else if (c > 0) {
833 break;
834 }
835 ++s;
836 }
837 return {s, MatchKind::kNe};
838 }
839
840 // Returns the position of the first value whose key is not less than k using
841 // binary search performed using plain compare.
842 template <typename K, typename Compare>
843 SearchResult<size_type, false> binary_search_impl(
844 const K &k, size_type s, size_type e, const Compare &comp,
845 std::false_type /* IsCompareTo */) const {
846 while (s != e) {
847 const size_type mid = (s + e) >> 1;
848 if (comp(key(mid), k)) {
849 s = mid + 1;
850 } else {
851 e = mid;
852 }
853 }
854 return SearchResult<size_type, false>{s};
855 }
856
857 // Returns the position of the first value whose key is not less than k using
858 // binary search performed using compare-to.
859 template <typename K, typename CompareTo>
860 SearchResult<size_type, true> binary_search_impl(
861 const K &k, size_type s, size_type e, const CompareTo &comp,
862 std::true_type /* IsCompareTo */) const {
863 if (params_type::template can_have_multiple_equivalent_keys<K>()) {
864 MatchKind exact_match = MatchKind::kNe;
865 while (s != e) {
866 const size_type mid = (s + e) >> 1;
867 const absl::weak_ordering c = comp(key(mid), k);
868 if (c < 0) {
869 s = mid + 1;
870 } else {
871 e = mid;
872 if (c == 0) {
873 // Need to return the first value whose key is not less than k,
874 // which requires continuing the binary search if there could be
875 // multiple equivalent keys.
876 exact_match = MatchKind::kEq;
877 }
878 }
879 }
880 return {s, exact_match};
881 } else { // Can't have multiple equivalent keys.
882 while (s != e) {
883 const size_type mid = (s + e) >> 1;
884 const absl::weak_ordering c = comp(key(mid), k);
885 if (c < 0) {
886 s = mid + 1;
887 } else if (c > 0) {
888 e = mid;
889 } else {
890 return {mid, MatchKind::kEq};
891 }
892 }
893 return {s, MatchKind::kNe};
894 }
895 }
896
897 // Returns whether key i is ordered correctly with respect to the other keys
898 // in the node. The motivation here is to detect comparators that violate
899 // transitivity. Note: we only do comparisons of keys on this node rather than
900 // the whole tree so that this is constant time.
901 template <typename Compare>
902 bool is_ordered_correctly(field_type i, const Compare &comp) const {
903 if (std::is_base_of<BtreeTestOnlyCheckedCompareOptOutBase,
904 Compare>::value ||
905 params_type::kIsKeyCompareStringAdapted) {
906 return true;
907 }
908
909 const auto compare = [&](field_type a, field_type b) {
910 const absl::weak_ordering cmp =
911 compare_internal::do_three_way_comparison(comp, key(a), key(b));
912 return cmp < 0 ? -1 : cmp > 0 ? 1 : 0;
913 };
914 int cmp = -1;
915 constexpr bool kCanHaveEquivKeys =
916 params_type::template can_have_multiple_equivalent_keys<key_type>();
917 for (field_type j = start(); j < finish(); ++j) {
918 if (j == i) {
919 if (cmp > 0) return false;
920 continue;
921 }
922 int new_cmp = compare(j, i);
923 if (new_cmp < cmp || (!kCanHaveEquivKeys && new_cmp == 0)) return false;
924 cmp = new_cmp;
925 }
926 return true;
927 }
928
929 // Emplaces a value at position i, shifting all existing values and
930 // children at positions >= i to the right by 1.
931 template <typename... Args>
932 void emplace_value(field_type i, allocator_type *alloc, Args &&...args);
933
934 // Removes the values at positions [i, i + to_erase), shifting all existing
935 // values and children after that range to the left by to_erase. Clears all
936 // children between [i, i + to_erase).
937 void remove_values(field_type i, field_type to_erase, allocator_type *alloc);
938
939 // Rebalances a node with its right sibling.
940 void rebalance_right_to_left(field_type to_move, btree_node *right,
941 allocator_type *alloc);
942 void rebalance_left_to_right(field_type to_move, btree_node *right,
943 allocator_type *alloc);
944
945 // Splits a node, moving a portion of the node's values to its right sibling.
946 void split(int insert_position, btree_node *dest, allocator_type *alloc);
947
948 // Merges a node with its right sibling, moving all of the values and the
949 // delimiting key in the parent node onto itself, and deleting the src node.
950 void merge(btree_node *src, allocator_type *alloc);
951
952 // Node allocation/deletion routines.
953 void init_leaf(field_type position, field_type max_count,
954 btree_node *parent) {
955 set_generation(0);
956 set_parent(parent);
957 set_position(position);
958 set_start(0);
959 set_finish(0);
960 set_max_count(max_count);
961 absl::container_internal::SanitizerPoisonMemoryRegion(
962 start_slot(), max_count * sizeof(slot_type));
963 }
964 void init_internal(field_type position, btree_node *parent) {
965 init_leaf(position, kNodeSlots, parent);
966 // Set `max_count` to a sentinel value to indicate that this node is
967 // internal.
968 set_max_count(kInternalNodeMaxCount);
969 absl::container_internal::SanitizerPoisonMemoryRegion(
970 &mutable_child(start()), (kNodeSlots + 1) * sizeof(btree_node *));
971 }
972
973 static void deallocate(const size_type size, btree_node *node,
974 allocator_type *alloc) {
975 absl::container_internal::SanitizerUnpoisonMemoryRegion(node, size);
976 absl::container_internal::Deallocate<Alignment()>(alloc, node, size);
977 }
978
979 // Deletes a node and all of its children.
980 static void clear_and_delete(btree_node *node, allocator_type *alloc);
981
982 private:
983 template <typename... Args>
984 void value_init(const field_type i, allocator_type *alloc, Args &&...args) {
985 next_generation();
986 absl::container_internal::SanitizerUnpoisonObject(slot(i));
987 params_type::construct(alloc, slot(i), std::forward<Args>(args)...);
988 }
989 void value_destroy(const field_type i, allocator_type *alloc) {
990 next_generation();
991 params_type::destroy(alloc, slot(i));
992 absl::container_internal::SanitizerPoisonObject(slot(i));
993 }
994 void value_destroy_n(const field_type i, const field_type n,
995 allocator_type *alloc) {
996 next_generation();
997 for (slot_type *s = slot(i), *end = slot(i + n); s != end; ++s) {
998 params_type::destroy(alloc, s);
999 absl::container_internal::SanitizerPoisonObject(s);
1000 }
1001 }
1002
1003 static void transfer(slot_type *dest, slot_type *src, allocator_type *alloc) {
1004 absl::container_internal::SanitizerUnpoisonObject(dest);
1005 params_type::transfer(alloc, dest, src);
1006 absl::container_internal::SanitizerPoisonObject(src);
1007 }
1008
1009 // Transfers value from slot `src_i` in `src_node` to slot `dest_i` in `this`.
1010 void transfer(const size_type dest_i, const size_type src_i,
1011 btree_node *src_node, allocator_type *alloc) {
1012 next_generation();
1013 transfer(slot(dest_i), src_node->slot(src_i), alloc);
1014 }
1015
1016 // Transfers `n` values starting at value `src_i` in `src_node` into the
1017 // values starting at value `dest_i` in `this`.
1018 void transfer_n(const size_type n, const size_type dest_i,
1019 const size_type src_i, btree_node *src_node,
1020 allocator_type *alloc) {
1021 next_generation();
1022 for (slot_type *src = src_node->slot(src_i), *end = src + n,
1023 *dest = slot(dest_i);
1024 src != end; ++src, ++dest) {
1025 transfer(dest, src, alloc);
1026 }
1027 }
1028
1029 // Same as above, except that we start at the end and work our way to the
1030 // beginning.
1031 void transfer_n_backward(const size_type n, const size_type dest_i,
1032 const size_type src_i, btree_node *src_node,
1033 allocator_type *alloc) {
1034 next_generation();
1035 for (slot_type *src = src_node->slot(src_i + n), *end = src - n,
1036 *dest = slot(dest_i + n);
1037 src != end; --src, --dest) {
1038 // If we modified the loop index calculations above to avoid the -1s here,
1039 // it would result in UB in the computation of `end` (and possibly `src`
1040 // as well, if n == 0), since slot() is effectively an array index and it
1041 // is UB to compute the address of any out-of-bounds array element except
1042 // for one-past-the-end.
1043 transfer(dest - 1, src - 1, alloc);
1044 }
1045 }
1046
1047 template <typename P>
1048 friend class btree;
1049 template <typename N, typename R, typename P>
1050 friend class btree_iterator;
1051 friend class BtreeNodePeer;
1052 friend struct btree_access;
1053 };
1054
1055 template <typename Node>
1056 bool AreNodesFromSameContainer(const Node *node_a, const Node *node_b) {
1057 // If either node is null, then give up on checking whether they're from the
1058 // same container. (If exactly one is null, then we'll trigger the
1059 // default-constructed assert in Equals.)
1060 if (node_a == nullptr || node_b == nullptr) return true;
1061 while (!node_a->is_root()) node_a = node_a->parent();
1062 while (!node_b->is_root()) node_b = node_b->parent();
1063 return node_a == node_b;
1064 }
1065
1066 class btree_iterator_generation_info_enabled {
1067 public:
1068 explicit btree_iterator_generation_info_enabled(uint32_t g)
1069 : generation_(g) {}
1070
1071 // Updates the generation. For use internally right before we return an
1072 // iterator to the user.
1073 template <typename Node>
1074 void update_generation(const Node *node) {
1075 if (node != nullptr) generation_ = node->generation();
1076 }
1077 uint32_t generation() const { return generation_; }
1078
1079 template <typename Node>
1080 void assert_valid_generation(const Node *node) const {
1081 if (node != nullptr && node->generation() != generation_) {
1082 ABSL_INTERNAL_LOG(
1083 FATAL,
1084 "Attempting to use an invalidated iterator. The corresponding b-tree "
1085 "container has been mutated since this iterator was constructed.");
1086 }
1087 }
1088
1089 private:
1090 // Used to check that the iterator hasn't been invalidated.
1091 uint32_t generation_;
1092 };
1093
1094 class btree_iterator_generation_info_disabled {
1095 public:
1096 explicit btree_iterator_generation_info_disabled(uint32_t) {}
1097 static void update_generation(const void *) {}
1098 static uint32_t generation() { return 0; }
1099 static void assert_valid_generation(const void *) {}
1100 };
1101
1102 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
1103 using btree_iterator_generation_info = btree_iterator_generation_info_enabled;
1104 #else
1105 using btree_iterator_generation_info = btree_iterator_generation_info_disabled;
1106 #endif
1107
1108 template <typename Node, typename Reference, typename Pointer>
1109 class btree_iterator : private btree_iterator_generation_info {
1110 using field_type = typename Node::field_type;
1111 using key_type = typename Node::key_type;
1112 using size_type = typename Node::size_type;
1113 using params_type = typename Node::params_type;
1114 using is_map_container = typename params_type::is_map_container;
1115
1116 using node_type = Node;
1117 using normal_node = typename std::remove_const<Node>::type;
1118 using const_node = const Node;
1119 using normal_pointer = typename params_type::pointer;
1120 using normal_reference = typename params_type::reference;
1121 using const_pointer = typename params_type::const_pointer;
1122 using const_reference = typename params_type::const_reference;
1123 using slot_type = typename params_type::slot_type;
1124
1125 using iterator =
1126 btree_iterator<normal_node, normal_reference, normal_pointer>;
1127 using const_iterator =
1128 btree_iterator<const_node, const_reference, const_pointer>;
1129
1130 public:
1131 // These aliases are public for std::iterator_traits.
1132 using difference_type = typename Node::difference_type;
1133 using value_type = typename params_type::value_type;
1134 using pointer = Pointer;
1135 using reference = Reference;
1136 using iterator_category = std::bidirectional_iterator_tag;
1137
1138 btree_iterator() : btree_iterator(nullptr, -1) {}
1139 explicit btree_iterator(Node *n) : btree_iterator(n, n->start()) {}
1140 btree_iterator(Node *n, int p)
1141 : btree_iterator_generation_info(n != nullptr ? n->generation()
1142 : ~uint32_t{}),
1143 node_(n),
1144 position_(p) {}
1145
1146 // NOTE: this SFINAE allows for implicit conversions from iterator to
1147 // const_iterator, but it specifically avoids hiding the copy constructor so
1148 // that the trivial one will be used when possible.
1149 template <typename N, typename R, typename P,
1150 absl::enable_if_t<
1151 std::is_same<btree_iterator<N, R, P>, iterator>::value &&
1152 std::is_same<btree_iterator, const_iterator>::value,
1153 int> = 0>
1154 btree_iterator(const btree_iterator<N, R, P> other) // NOLINT
1155 : btree_iterator_generation_info(other),
1156 node_(other.node_),
1157 position_(other.position_) {}
1158
1159 bool operator==(const iterator &other) const {
1160 return Equals(other);
1161 }
1162 bool operator==(const const_iterator &other) const {
1163 return Equals(other);
1164 }
1165 bool operator!=(const iterator &other) const {
1166 return !Equals(other);
1167 }
1168 bool operator!=(const const_iterator &other) const {
1169 return !Equals(other);
1170 }
1171
1172 // Returns n such that n calls to ++other yields *this.
1173 // Precondition: n exists.
1174 difference_type operator-(const_iterator other) const {
1175 if (node_ == other.node_) {
1176 if (node_->is_leaf()) return position_ - other.position_;
1177 if (position_ == other.position_) return 0;
1178 }
1179 return distance_slow(other);
1180 }
1181
1182 // Accessors for the key/value the iterator is pointing at.
1183 reference operator*() const {
1184 ABSL_HARDENING_ASSERT(node_ != nullptr);
1185 assert_valid_generation(node_);
1186 ABSL_HARDENING_ASSERT(position_ >= node_->start());
1187 if (position_ >= node_->finish()) {
1188 ABSL_HARDENING_ASSERT(!IsEndIterator() && "Dereferencing end() iterator");
1189 ABSL_HARDENING_ASSERT(position_ < node_->finish());
1190 }
1191 return node_->value(static_cast<field_type>(position_));
1192 }
1193 pointer operator->() const { return &operator*(); }
1194
1195 btree_iterator &operator++() {
1196 increment();
1197 return *this;
1198 }
1199 btree_iterator &operator--() {
1200 decrement();
1201 return *this;
1202 }
1203 btree_iterator operator++(int) {
1204 btree_iterator tmp = *this;
1205 ++*this;
1206 return tmp;
1207 }
1208 btree_iterator operator--(int) {
1209 btree_iterator tmp = *this;
1210 --*this;
1211 return tmp;
1212 }
1213
1214 private:
1215 friend iterator;
1216 friend const_iterator;
1217 template <typename Params>
1218 friend class btree;
1219 template <typename Tree>
1220 friend class btree_container;
1221 template <typename Tree>
1222 friend class btree_set_container;
1223 template <typename Tree>
1224 friend class btree_map_container;
1225 template <typename Tree>
1226 friend class btree_multiset_container;
1227 template <typename TreeType, typename CheckerType>
1228 friend class base_checker;
1229 friend struct btree_access;
1230
1231 // This SFINAE allows explicit conversions from const_iterator to
1232 // iterator, but also avoids hiding the copy constructor.
1233 // NOTE: the const_cast is safe because this constructor is only called by
1234 // non-const methods and the container owns the nodes.
1235 template <typename N, typename R, typename P,
1236 absl::enable_if_t<
1237 std::is_same<btree_iterator<N, R, P>, const_iterator>::value &&
1238 std::is_same<btree_iterator, iterator>::value,
1239 int> = 0>
1240 explicit btree_iterator(const btree_iterator<N, R, P> other)
1241 : btree_iterator_generation_info(other.generation()),
1242 node_(const_cast<node_type *>(other.node_)),
1243 position_(other.position_) {}
1244
1245 bool Equals(const const_iterator other) const {
1246 ABSL_HARDENING_ASSERT(((node_ == nullptr && other.node_ == nullptr) ||
1247 (node_ != nullptr && other.node_ != nullptr)) &&
1248 "Comparing default-constructed iterator with "
1249 "non-default-constructed iterator.");
1250 // Note: we use assert instead of ABSL_HARDENING_ASSERT here because this
1251 // changes the complexity of Equals from O(1) to O(log(N) + log(M)) where
1252 // N/M are sizes of the containers containing node_/other.node_.
1253 assert(AreNodesFromSameContainer(node_, other.node_) &&
1254 "Comparing iterators from different containers.");
1255 assert_valid_generation(node_);
1256 other.assert_valid_generation(other.node_);
1257 return node_ == other.node_ && position_ == other.position_;
1258 }
1259
1260 bool IsEndIterator() const {
1261 if (position_ != node_->finish()) return false;
1262 node_type *node = node_;
1263 while (!node->is_root()) {
1264 if (node->position() != node->parent()->finish()) return false;
1265 node = node->parent();
1266 }
1267 return true;
1268 }
1269
1270 // Returns n such that n calls to ++other yields *this.
1271 // Precondition: n exists && (this->node_ != other.node_ ||
1272 // !this->node_->is_leaf() || this->position_ != other.position_).
1273 difference_type distance_slow(const_iterator other) const;
1274
1275 // Increment/decrement the iterator.
1276 void increment() {
1277 assert_valid_generation(node_);
1278 if (node_->is_leaf() && ++position_ < node_->finish()) {
1279 return;
1280 }
1281 increment_slow();
1282 }
1283 void increment_slow();
1284
1285 void decrement() {
1286 assert_valid_generation(node_);
1287 if (node_->is_leaf() && --position_ >= node_->start()) {
1288 return;
1289 }
1290 decrement_slow();
1291 }
1292 void decrement_slow();
1293
1294 const key_type &key() const {
1295 return node_->key(static_cast<size_type>(position_));
1296 }
1297 decltype(std::declval<Node *>()->slot(0)) slot() {
1298 return node_->slot(static_cast<size_type>(position_));
1299 }
1300
1301 void update_generation() {
1302 btree_iterator_generation_info::update_generation(node_);
1303 }
1304
1305 // The node in the tree the iterator is pointing at.
1306 Node *node_;
1307 // The position within the node of the tree the iterator is pointing at.
1308 // NOTE: this is an int rather than a field_type because iterators can point
1309 // to invalid positions (such as -1) in certain circumstances.
1310 int position_;
1311 };
1312
1313 template <typename Params>
1314 class btree {
1315 using node_type = btree_node<Params>;
1316 using is_key_compare_to = typename Params::is_key_compare_to;
1317 using field_type = typename node_type::field_type;
1318
1319 // We use a static empty node for the root/leftmost/rightmost of empty btrees
1320 // in order to avoid branching in begin()/end().
1321 struct alignas(node_type::Alignment()) EmptyNodeType : node_type {
1322 using field_type = typename node_type::field_type;
1323 node_type *parent;
1324 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
1325 uint32_t generation = 0;
1326 #endif
1327 field_type position = 0;
1328 field_type start = 0;
1329 field_type finish = 0;
1330 // max_count must be != kInternalNodeMaxCount (so that this node is regarded
1331 // as a leaf node). max_count() is never called when the tree is empty.
1332 field_type max_count = node_type::kInternalNodeMaxCount + 1;
1333
1334 #ifdef _MSC_VER
1335 // MSVC has constexpr code generations bugs here.
1336 EmptyNodeType() : parent(this) {}
1337 #else
1338 explicit constexpr EmptyNodeType(node_type *p) : parent(p) {}
1339 #endif
1340 };
1341
1342 static node_type *EmptyNode() {
1343 #ifdef _MSC_VER
1344 static EmptyNodeType *empty_node = new EmptyNodeType;
1345 // This assert fails on some other construction methods.
1346 assert(empty_node->parent == empty_node);
1347 return empty_node;
1348 #else
1349 static constexpr EmptyNodeType empty_node(
1350 const_cast<EmptyNodeType *>(&empty_node));
1351 return const_cast<EmptyNodeType *>(&empty_node);
1352 #endif
1353 }
1354
1355 enum : uint32_t {
1356 kNodeSlots = node_type::kNodeSlots,
1357 kMinNodeValues = kNodeSlots / 2,
1358 };
1359
1360 struct node_stats {
1361 using size_type = typename Params::size_type;
1362
1363 node_stats(size_type l, size_type i) : leaf_nodes(l), internal_nodes(i) {}
1364
1365 node_stats &operator+=(const node_stats &other) {
1366 leaf_nodes += other.leaf_nodes;
1367 internal_nodes += other.internal_nodes;
1368 return *this;
1369 }
1370
1371 size_type leaf_nodes;
1372 size_type internal_nodes;
1373 };
1374
1375 public:
1376 using key_type = typename Params::key_type;
1377 using value_type = typename Params::value_type;
1378 using size_type = typename Params::size_type;
1379 using difference_type = typename Params::difference_type;
1380 using key_compare = typename Params::key_compare;
1381 using original_key_compare = typename Params::original_key_compare;
1382 using value_compare = typename Params::value_compare;
1383 using allocator_type = typename Params::allocator_type;
1384 using reference = typename Params::reference;
1385 using const_reference = typename Params::const_reference;
1386 using pointer = typename Params::pointer;
1387 using const_pointer = typename Params::const_pointer;
1388 using iterator =
1389 typename btree_iterator<node_type, reference, pointer>::iterator;
1390 using const_iterator = typename iterator::const_iterator;
1391 using reverse_iterator = std::reverse_iterator<iterator>;
1392 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
1393 using node_handle_type = node_handle<Params, Params, allocator_type>;
1394
1395 // Internal types made public for use by btree_container types.
1396 using params_type = Params;
1397 using slot_type = typename Params::slot_type;
1398
1399 private:
1400 // Copies or moves (depending on the template parameter) the values in
1401 // other into this btree in their order in other. This btree must be empty
1402 // before this method is called. This method is used in copy construction,
1403 // copy assignment, and move assignment.
1404 template <typename Btree>
1405 void copy_or_move_values_in_order(Btree &other);
1406
1407 // Validates that various assumptions/requirements are true at compile time.
1408 constexpr static bool static_assert_validation();
1409
1410 public:
1411 btree(const key_compare &comp, const allocator_type &alloc)
1412 : root_(EmptyNode()), rightmost_(comp, alloc, EmptyNode()), size_(0) {}
1413
1414 btree(const btree &other) : btree(other, other.allocator()) {}
1415 btree(const btree &other, const allocator_type &alloc)
1416 : btree(other.key_comp(), alloc) {
1417 copy_or_move_values_in_order(other);
1418 }
1419 btree(btree &&other) noexcept
1420 : root_(absl::exchange(other.root_, EmptyNode())),
1421 rightmost_(std::move(other.rightmost_)),
1422 size_(absl::exchange(other.size_, 0u)) {
1423 other.mutable_rightmost() = EmptyNode();
1424 }
1425 btree(btree &&other, const allocator_type &alloc)
1426 : btree(other.key_comp(), alloc) {
1427 if (alloc == other.allocator()) {
1428 swap(other);
1429 } else {
1430 // Move values from `other` one at a time when allocators are different.
1431 copy_or_move_values_in_order(other);
1432 }
1433 }
1434
1435 ~btree() {
1436 // Put static_asserts in destructor to avoid triggering them before the type
1437 // is complete.
1438 static_assert(static_assert_validation(), "This call must be elided.");
1439 clear();
1440 }
1441
1442 // Assign the contents of other to *this.
1443 btree &operator=(const btree &other);
1444 btree &operator=(btree &&other) noexcept;
1445
1446 iterator begin() { return iterator(leftmost()); }
1447 const_iterator begin() const { return const_iterator(leftmost()); }
1448 iterator end() { return iterator(rightmost(), rightmost()->finish()); }
1449 const_iterator end() const {
1450 return const_iterator(rightmost(), rightmost()->finish());
1451 }
1452 reverse_iterator rbegin() { return reverse_iterator(end()); }
1453 const_reverse_iterator rbegin() const {
1454 return const_reverse_iterator(end());
1455 }
1456 reverse_iterator rend() { return reverse_iterator(begin()); }
1457 const_reverse_iterator rend() const {
1458 return const_reverse_iterator(begin());
1459 }
1460
1461 // Finds the first element whose key is not less than `key`.
1462 template <typename K>
1463 iterator lower_bound(const K &key) {
1464 return internal_end(internal_lower_bound(key).value);
1465 }
1466 template <typename K>
1467 const_iterator lower_bound(const K &key) const {
1468 return internal_end(internal_lower_bound(key).value);
1469 }
1470
1471 // Finds the first element whose key is not less than `key` and also returns
1472 // whether that element is equal to `key`.
1473 template <typename K>
1474 std::pair<iterator, bool> lower_bound_equal(const K &key) const;
1475
1476 // Finds the first element whose key is greater than `key`.
1477 template <typename K>
1478 iterator upper_bound(const K &key) {
1479 return internal_end(internal_upper_bound(key));
1480 }
1481 template <typename K>
1482 const_iterator upper_bound(const K &key) const {
1483 return internal_end(internal_upper_bound(key));
1484 }
1485
1486 // Finds the range of values which compare equal to key. The first member of
1487 // the returned pair is equal to lower_bound(key). The second member of the
1488 // pair is equal to upper_bound(key).
1489 template <typename K>
1490 std::pair<iterator, iterator> equal_range(const K &key);
1491 template <typename K>
1492 std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
1493 return const_cast<btree *>(this)->equal_range(key);
1494 }
1495
1496 // Inserts a value into the btree only if it does not already exist. The
1497 // boolean return value indicates whether insertion succeeded or failed.
1498 // Requirement: if `key` already exists in the btree, does not consume `args`.
1499 // Requirement: `key` is never referenced after consuming `args`.
1500 template <typename K, typename... Args>
1501 std::pair<iterator, bool> insert_unique(const K &key, Args &&...args);
1502
1503 // Inserts with hint. Checks to see if the value should be placed immediately
1504 // before `position` in the tree. If so, then the insertion will take
1505 // amortized constant time. If not, the insertion will take amortized
1506 // logarithmic time as if a call to insert_unique() were made.
1507 // Requirement: if `key` already exists in the btree, does not consume `args`.
1508 // Requirement: `key` is never referenced after consuming `args`.
1509 template <typename K, typename... Args>
1510 std::pair<iterator, bool> insert_hint_unique(iterator position, const K &key,
1511 Args &&...args);
1512
1513 // Insert a range of values into the btree.
1514 // Note: the first overload avoids constructing a value_type if the key
1515 // already exists in the btree.
1516 template <typename InputIterator,
1517 typename = decltype(std::declval<const key_compare &>()(
1518 params_type::key(*std::declval<InputIterator>()),
1519 std::declval<const key_type &>()))>
1520 void insert_iterator_unique(InputIterator b, InputIterator e, int);
1521 // We need the second overload for cases in which we need to construct a
1522 // value_type in order to compare it with the keys already in the btree.
1523 template <typename InputIterator>
1524 void insert_iterator_unique(InputIterator b, InputIterator e, char);
1525
1526 // Inserts a value into the btree.
1527 template <typename ValueType>
1528 iterator insert_multi(const key_type &key, ValueType &&v);
1529
1530 // Inserts a value into the btree.
1531 template <typename ValueType>
1532 iterator insert_multi(ValueType &&v) {
1533 return insert_multi(params_type::key(v), std::forward<ValueType>(v));
1534 }
1535
1536 // Insert with hint. Check to see if the value should be placed immediately
1537 // before position in the tree. If it does, then the insertion will take
1538 // amortized constant time. If not, the insertion will take amortized
1539 // logarithmic time as if a call to insert_multi(v) were made.
1540 template <typename ValueType>
1541 iterator insert_hint_multi(iterator position, ValueType &&v);
1542
1543 // Insert a range of values into the btree.
1544 template <typename InputIterator>
1545 void insert_iterator_multi(InputIterator b,
1546 InputIterator e);
1547
1548 // Erase the specified iterator from the btree. The iterator must be valid
1549 // (i.e. not equal to end()). Return an iterator pointing to the node after
1550 // the one that was erased (or end() if none exists).
1551 // Requirement: does not read the value at `*iter`.
1552 iterator erase(iterator iter);
1553
1554 // Erases range. Returns the number of keys erased and an iterator pointing
1555 // to the element after the last erased element.
1556 std::pair<size_type, iterator> erase_range(iterator begin, iterator end);
1557
1558 // Finds an element with key equivalent to `key` or returns `end()` if `key`
1559 // is not present.
1560 template <typename K>
1561 iterator find(const K &key) {
1562 return internal_end(internal_find(key));
1563 }
1564 template <typename K>
1565 const_iterator find(const K &key) const {
1566 return internal_end(internal_find(key));
1567 }
1568
1569 // Clear the btree, deleting all of the values it contains.
1570 void clear();
1571
1572 // Swaps the contents of `this` and `other`.
1573 void swap(btree &other);
1574
1575 const key_compare &key_comp() const noexcept {
1576 return rightmost_.template get<0>();
1577 }
1578 template <typename K1, typename K2>
1579 bool compare_keys(const K1 &a, const K2 &b) const {
1580 return compare_internal::compare_result_as_less_than(key_comp()(a, b));
1581 }
1582
1583 value_compare value_comp() const {
1584 return value_compare(original_key_compare(key_comp()));
1585 }
1586
1587 // Verifies the structure of the btree.
1588 void verify() const;
1589
1590 // Size routines.
1591 size_type size() const { return size_; }
1592 size_type max_size() const { return (std::numeric_limits<size_type>::max)(); }
1593 bool empty() const { return size_ == 0; }
1594
1595 // The height of the btree. An empty tree will have height 0.
1596 size_type height() const {
1597 size_type h = 0;
1598 if (!empty()) {
1599 // Count the length of the chain from the leftmost node up to the
1600 // root. We actually count from the root back around to the level below
1601 // the root, but the calculation is the same because of the circularity
1602 // of that traversal.
1603 const node_type *n = root();
1604 do {
1605 ++h;
1606 n = n->parent();
1607 } while (n != root());
1608 }
1609 return h;
1610 }
1611
1612 // The number of internal, leaf and total nodes used by the btree.
1613 size_type leaf_nodes() const { return internal_stats(root()).leaf_nodes; }
1614 size_type internal_nodes() const {
1615 return internal_stats(root()).internal_nodes;
1616 }
1617 size_type nodes() const {
1618 node_stats stats = internal_stats(root());
1619 return stats.leaf_nodes + stats.internal_nodes;
1620 }
1621
1622 // The total number of bytes used by the btree.
1623 // TODO(b/169338300): update to support node_btree_*.
1624 size_type bytes_used() const {
1625 node_stats stats = internal_stats(root());
1626 if (stats.leaf_nodes == 1 && stats.internal_nodes == 0) {
1627 return sizeof(*this) + node_type::LeafSize(root()->max_count());
1628 } else {
1629 return sizeof(*this) + stats.leaf_nodes * node_type::LeafSize() +
1630 stats.internal_nodes * node_type::InternalSize();
1631 }
1632 }
1633
1634 // The average number of bytes used per value stored in the btree assuming
1635 // random insertion order.
1636 static double average_bytes_per_value() {
1637 // The expected number of values per node with random insertion order is the
1638 // average of the maximum and minimum numbers of values per node.
1639 const double expected_values_per_node = (kNodeSlots + kMinNodeValues) / 2.0;
1640 return node_type::LeafSize() / expected_values_per_node;
1641 }
1642
1643 // The fullness of the btree. Computed as the number of elements in the btree
1644 // divided by the maximum number of elements a tree with the current number
1645 // of nodes could hold. A value of 1 indicates perfect space
1646 // utilization. Smaller values indicate space wastage.
1647 // Returns 0 for empty trees.
1648 double fullness() const {
1649 if (empty()) return 0.0;
1650 return static_cast<double>(size()) / (nodes() * kNodeSlots);
1651 }
1652 // The overhead of the btree structure in bytes per node. Computed as the
1653 // total number of bytes used by the btree minus the number of bytes used for
1654 // storing elements divided by the number of elements.
1655 // Returns 0 for empty trees.
1656 double overhead() const {
1657 if (empty()) return 0.0;
1658 return (bytes_used() - size() * sizeof(value_type)) /
1659 static_cast<double>(size());
1660 }
1661
1662 // The allocator used by the btree.
1663 allocator_type get_allocator() const { return allocator(); }
1664
1665 private:
1666 friend struct btree_access;
1667
1668 // Internal accessor routines.
1669 node_type *root() { return root_; }
1670 const node_type *root() const { return root_; }
1671 node_type *&mutable_root() noexcept { return root_; }
1672 node_type *rightmost() { return rightmost_.template get<2>(); }
1673 const node_type *rightmost() const { return rightmost_.template get<2>(); }
1674 node_type *&mutable_rightmost() noexcept {
1675 return rightmost_.template get<2>();
1676 }
1677 key_compare *mutable_key_comp() noexcept {
1678 return &rightmost_.template get<0>();
1679 }
1680
1681 // The leftmost node is stored as the parent of the root node.
1682 node_type *leftmost() { return root()->parent(); }
1683 const node_type *leftmost() const { return root()->parent(); }
1684
1685 // Allocator routines.
1686 allocator_type *mutable_allocator() noexcept {
1687 return &rightmost_.template get<1>();
1688 }
1689 const allocator_type &allocator() const noexcept {
1690 return rightmost_.template get<1>();
1691 }
1692
1693 // Allocates a correctly aligned node of at least size bytes using the
1694 // allocator.
1695 node_type *allocate(size_type size) {
1696 return reinterpret_cast<node_type *>(
1697 absl::container_internal::Allocate<node_type::Alignment()>(
1698 mutable_allocator(), size));
1699 }
1700
1701 // Node creation/deletion routines.
1702 node_type *new_internal_node(field_type position, node_type *parent) {
1703 node_type *n = allocate(node_type::InternalSize());
1704 n->init_internal(position, parent);
1705 return n;
1706 }
1707 node_type *new_leaf_node(field_type position, node_type *parent) {
1708 node_type *n = allocate(node_type::LeafSize());
1709 n->init_leaf(position, kNodeSlots, parent);
1710 return n;
1711 }
1712 node_type *new_leaf_root_node(field_type max_count) {
1713 node_type *n = allocate(node_type::LeafSize(max_count));
1714 n->init_leaf(/*position=*/0, max_count, /*parent=*/n);
1715 return n;
1716 }
1717
1718 // Deletion helper routines.
1719 iterator rebalance_after_delete(iterator iter);
1720
1721 // Rebalances or splits the node iter points to.
1722 void rebalance_or_split(iterator *iter);
1723
1724 // Merges the values of left, right and the delimiting key on their parent
1725 // onto left, removing the delimiting key and deleting right.
1726 void merge_nodes(node_type *left, node_type *right);
1727
1728 // Tries to merge node with its left or right sibling, and failing that,
1729 // rebalance with its left or right sibling. Returns true if a merge
1730 // occurred, at which point it is no longer valid to access node. Returns
1731 // false if no merging took place.
1732 bool try_merge_or_rebalance(iterator *iter);
1733
1734 // Tries to shrink the height of the tree by 1.
1735 void try_shrink();
1736
1737 iterator internal_end(iterator iter) {
1738 return iter.node_ != nullptr ? iter : end();
1739 }
1740 const_iterator internal_end(const_iterator iter) const {
1741 return iter.node_ != nullptr ? iter : end();
1742 }
1743
1744 // Emplaces a value into the btree immediately before iter. Requires that
1745 // key(v) <= iter.key() and (--iter).key() <= key(v).
1746 template <typename... Args>
1747 iterator internal_emplace(iterator iter, Args &&...args);
1748
1749 // Returns an iterator pointing to the first value >= the value "iter" is
1750 // pointing at. Note that "iter" might be pointing to an invalid location such
1751 // as iter.position_ == iter.node_->finish(). This routine simply moves iter
1752 // up in the tree to a valid location. Requires: iter.node_ is non-null.
1753 template <typename IterType>
1754 static IterType internal_last(IterType iter);
1755
1756 // Returns an iterator pointing to the leaf position at which key would
1757 // reside in the tree, unless there is an exact match - in which case, the
1758 // result may not be on a leaf. When there's a three-way comparator, we can
1759 // return whether there was an exact match. This allows the caller to avoid a
1760 // subsequent comparison to determine if an exact match was made, which is
1761 // important for keys with expensive comparison, such as strings.
1762 template <typename K>
1763 SearchResult<iterator, is_key_compare_to::value> internal_locate(
1764 const K &key) const;
1765
1766 // Internal routine which implements lower_bound().
1767 template <typename K>
1768 SearchResult<iterator, is_key_compare_to::value> internal_lower_bound(
1769 const K &key) const;
1770
1771 // Internal routine which implements upper_bound().
1772 template <typename K>
1773 iterator internal_upper_bound(const K &key) const;
1774
1775 // Internal routine which implements find().
1776 template <typename K>
1777 iterator internal_find(const K &key) const;
1778
1779 // Verifies the tree structure of node.
1780 size_type internal_verify(const node_type *node, const key_type *lo,
1781 const key_type *hi) const;
1782
1783 node_stats internal_stats(const node_type *node) const {
1784 // The root can be a static empty node.
1785 if (node == nullptr || (node == root() && empty())) {
1786 return node_stats(0, 0);
1787 }
1788 if (node->is_leaf()) {
1789 return node_stats(1, 0);
1790 }
1791 node_stats res(0, 1);
1792 for (int i = node->start(); i <= node->finish(); ++i) {
1793 res += internal_stats(node->child(i));
1794 }
1795 return res;
1796 }
1797
1798 node_type *root_;
1799
1800 // A pointer to the rightmost node. Note that the leftmost node is stored as
1801 // the root's parent. We use compressed tuple in order to save space because
1802 // key_compare and allocator_type are usually empty.
1803 absl::container_internal::CompressedTuple<key_compare, allocator_type,
1804 node_type *>
1805 rightmost_;
1806
1807 // Number of values.
1808 size_type size_;
1809 };
1810
1811 ////
1812 // btree_node methods
1813 template <typename P>
1814 template <typename... Args>
1815 inline void btree_node<P>::emplace_value(const field_type i,
1816 allocator_type *alloc,
1817 Args &&...args) {
1818 assert(i >= start());
1819 assert(i <= finish());
1820 // Shift old values to create space for new value and then construct it in
1821 // place.
1822 if (i < finish()) {
1823 transfer_n_backward(finish() - i, /*dest_i=*/i + 1, /*src_i=*/i, this,
1824 alloc);
1825 }
1826 value_init(static_cast<field_type>(i), alloc, std::forward<Args>(args)...);
1827 set_finish(finish() + 1);
1828
1829 if (is_internal() && finish() > i + 1) {
1830 for (field_type j = finish(); j > i + 1; --j) {
1831 set_child(j, child(j - 1));
1832 }
1833 clear_child(i + 1);
1834 }
1835 }
1836
1837 template <typename P>
1838 inline void btree_node<P>::remove_values(const field_type i,
1839 const field_type to_erase,
1840 allocator_type *alloc) {
1841 // Transfer values after the removed range into their new places.
1842 value_destroy_n(i, to_erase, alloc);
1843 const field_type orig_finish = finish();
1844 const field_type src_i = i + to_erase;
1845 transfer_n(orig_finish - src_i, i, src_i, this, alloc);
1846
1847 if (is_internal()) {
1848 // Delete all children between begin and end.
1849 for (field_type j = 0; j < to_erase; ++j) {
1850 clear_and_delete(child(i + j + 1), alloc);
1851 }
1852 // Rotate children after end into new positions.
1853 for (field_type j = i + to_erase + 1; j <= orig_finish; ++j) {
1854 set_child(j - to_erase, child(j));
1855 clear_child(j);
1856 }
1857 }
1858 set_finish(orig_finish - to_erase);
1859 }
1860
1861 template <typename P>
1862 void btree_node<P>::rebalance_right_to_left(field_type to_move,
1863 btree_node *right,
1864 allocator_type *alloc) {
1865 assert(parent() == right->parent());
1866 assert(position() + 1 == right->position());
1867 assert(right->count() >= count());
1868 assert(to_move >= 1);
1869 assert(to_move <= right->count());
1870
1871 // 1) Move the delimiting value in the parent to the left node.
1872 transfer(finish(), position(), parent(), alloc);
1873
1874 // 2) Move the (to_move - 1) values from the right node to the left node.
1875 transfer_n(to_move - 1, finish() + 1, right->start(), right, alloc);
1876
1877 // 3) Move the new delimiting value to the parent from the right node.
1878 parent()->transfer(position(), right->start() + to_move - 1, right, alloc);
1879
1880 // 4) Shift the values in the right node to their correct positions.
1881 right->transfer_n(right->count() - to_move, right->start(),
1882 right->start() + to_move, right, alloc);
1883
1884 if (is_internal()) {
1885 // Move the child pointers from the right to the left node.
1886 for (field_type i = 0; i < to_move; ++i) {
1887 init_child(finish() + i + 1, right->child(i));
1888 }
1889 for (field_type i = right->start(); i <= right->finish() - to_move; ++i) {
1890 assert(i + to_move <= right->max_count());
1891 right->init_child(i, right->child(i + to_move));
1892 right->clear_child(i + to_move);
1893 }
1894 }
1895
1896 // Fixup `finish` on the left and right nodes.
1897 set_finish(finish() + to_move);
1898 right->set_finish(right->finish() - to_move);
1899 }
1900
1901 template <typename P>
1902 void btree_node<P>::rebalance_left_to_right(field_type to_move,
1903 btree_node *right,
1904 allocator_type *alloc) {
1905 assert(parent() == right->parent());
1906 assert(position() + 1 == right->position());
1907 assert(count() >= right->count());
1908 assert(to_move >= 1);
1909 assert(to_move <= count());
1910
1911 // Values in the right node are shifted to the right to make room for the
1912 // new to_move values. Then, the delimiting value in the parent and the
1913 // other (to_move - 1) values in the left node are moved into the right node.
1914 // Lastly, a new delimiting value is moved from the left node into the
1915 // parent, and the remaining empty left node entries are destroyed.
1916
1917 // 1) Shift existing values in the right node to their correct positions.
1918 right->transfer_n_backward(right->count(), right->start() + to_move,
1919 right->start(), right, alloc);
1920
1921 // 2) Move the delimiting value in the parent to the right node.
1922 right->transfer(right->start() + to_move - 1, position(), parent(), alloc);
1923
1924 // 3) Move the (to_move - 1) values from the left node to the right node.
1925 right->transfer_n(to_move - 1, right->start(), finish() - (to_move - 1), this,
1926 alloc);
1927
1928 // 4) Move the new delimiting value to the parent from the left node.
1929 parent()->transfer(position(), finish() - to_move, this, alloc);
1930
1931 if (is_internal()) {
1932 // Move the child pointers from the left to the right node.
1933 for (field_type i = right->finish() + 1; i > right->start(); --i) {
1934 right->init_child(i - 1 + to_move, right->child(i - 1));
1935 right->clear_child(i - 1);
1936 }
1937 for (field_type i = 1; i <= to_move; ++i) {
1938 right->init_child(i - 1, child(finish() - to_move + i));
1939 clear_child(finish() - to_move + i);
1940 }
1941 }
1942
1943 // Fixup the counts on the left and right nodes.
1944 set_finish(finish() - to_move);
1945 right->set_finish(right->finish() + to_move);
1946 }
1947
1948 template <typename P>
1949 void btree_node<P>::split(const int insert_position, btree_node *dest,
1950 allocator_type *alloc) {
1951 assert(dest->count() == 0);
1952 assert(max_count() == kNodeSlots);
1953 assert(position() + 1 == dest->position());
1954 assert(parent() == dest->parent());
1955
1956 // We bias the split based on the position being inserted. If we're
1957 // inserting at the beginning of the left node then bias the split to put
1958 // more values on the right node. If we're inserting at the end of the
1959 // right node then bias the split to put more values on the left node.
1960 if (insert_position == start()) {
1961 dest->set_finish(dest->start() + finish() - 1);
1962 } else if (insert_position == kNodeSlots) {
1963 dest->set_finish(dest->start());
1964 } else {
1965 dest->set_finish(dest->start() + count() / 2);
1966 }
1967 set_finish(finish() - dest->count());
1968 assert(count() >= 1);
1969
1970 // Move values from the left sibling to the right sibling.
1971 dest->transfer_n(dest->count(), dest->start(), finish(), this, alloc);
1972
1973 // The split key is the largest value in the left sibling.
1974 --mutable_finish();
1975 parent()->emplace_value(position(), alloc, finish_slot());
1976 value_destroy(finish(), alloc);
1977 parent()->set_child_noupdate_position(position() + 1, dest);
1978
1979 if (is_internal()) {
1980 for (field_type i = dest->start(), j = finish() + 1; i <= dest->finish();
1981 ++i, ++j) {
1982 assert(child(j) != nullptr);
1983 dest->init_child(i, child(j));
1984 clear_child(j);
1985 }
1986 }
1987 }
1988
1989 template <typename P>
1990 void btree_node<P>::merge(btree_node *src, allocator_type *alloc) {
1991 assert(parent() == src->parent());
1992 assert(position() + 1 == src->position());
1993
1994 // Move the delimiting value to the left node.
1995 value_init(finish(), alloc, parent()->slot(position()));
1996
1997 // Move the values from the right to the left node.
1998 transfer_n(src->count(), finish() + 1, src->start(), src, alloc);
1999
2000 if (is_internal()) {
2001 // Move the child pointers from the right to the left node.
2002 for (field_type i = src->start(), j = finish() + 1; i <= src->finish();
2003 ++i, ++j) {
2004 init_child(j, src->child(i));
2005 src->clear_child(i);
2006 }
2007 }
2008
2009 // Fixup `finish` on the src and dest nodes.
2010 set_finish(start() + 1 + count() + src->count());
2011 src->set_finish(src->start());
2012
2013 // Remove the value on the parent node and delete the src node.
2014 parent()->remove_values(position(), /*to_erase=*/1, alloc);
2015 }
2016
2017 template <typename P>
2018 void btree_node<P>::clear_and_delete(btree_node *node, allocator_type *alloc) {
2019 if (node->is_leaf()) {
2020 node->value_destroy_n(node->start(), node->count(), alloc);
2021 deallocate(LeafSize(node->max_count()), node, alloc);
2022 return;
2023 }
2024 if (node->count() == 0) {
2025 deallocate(InternalSize(), node, alloc);
2026 return;
2027 }
2028
2029 // The parent of the root of the subtree we are deleting.
2030 btree_node *delete_root_parent = node->parent();
2031
2032 // Navigate to the leftmost leaf under node, and then delete upwards.
2033 while (node->is_internal()) node = node->start_child();
2034 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
2035 // When generations are enabled, we delete the leftmost leaf last in case it's
2036 // the parent of the root and we need to check whether it's a leaf before we
2037 // can update the root's generation.
2038 // TODO(ezb): if we change btree_node::is_root to check a bool inside the node
2039 // instead of checking whether the parent is a leaf, we can remove this logic.
2040 btree_node *leftmost_leaf = node;
2041 #endif
2042 // Use `size_type` because `pos` needs to be able to hold `kNodeSlots+1`,
2043 // which isn't guaranteed to be a valid `field_type`.
2044 size_type pos = node->position();
2045 btree_node *parent = node->parent();
2046 for (;;) {
2047 // In each iteration of the next loop, we delete one leaf node and go right.
2048 assert(pos <= parent->finish());
2049 do {
2050 node = parent->child(static_cast<field_type>(pos));
2051 if (node->is_internal()) {
2052 // Navigate to the leftmost leaf under node.
2053 while (node->is_internal()) node = node->start_child();
2054 pos = node->position();
2055 parent = node->parent();
2056 }
2057 node->value_destroy_n(node->start(), node->count(), alloc);
2058 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
2059 if (leftmost_leaf != node)
2060 #endif
2061 deallocate(LeafSize(node->max_count()), node, alloc);
2062 ++pos;
2063 } while (pos <= parent->finish());
2064
2065 // Once we've deleted all children of parent, delete parent and go up/right.
2066 assert(pos > parent->finish());
2067 do {
2068 node = parent;
2069 pos = node->position();
2070 parent = node->parent();
2071 node->value_destroy_n(node->start(), node->count(), alloc);
2072 deallocate(InternalSize(), node, alloc);
2073 if (parent == delete_root_parent) {
2074 #ifdef ABSL_BTREE_ENABLE_GENERATIONS
2075 deallocate(LeafSize(leftmost_leaf->max_count()), leftmost_leaf, alloc);
2076 #endif
2077 return;
2078 }
2079 ++pos;
2080 } while (pos > parent->finish());
2081 }
2082 }
2083
2084 ////
2085 // btree_iterator methods
2086
2087 // Note: the implementation here is based on btree_node::clear_and_delete.
2088 template <typename N, typename R, typename P>
2089 auto btree_iterator<N, R, P>::distance_slow(const_iterator other) const
2090 -> difference_type {
2091 const_iterator begin = other;
2092 const_iterator end = *this;
2093 assert(begin.node_ != end.node_ || !begin.node_->is_leaf() ||
2094 begin.position_ != end.position_);
2095
2096 const node_type *node = begin.node_;
2097 // We need to compensate for double counting if begin.node_ is a leaf node.
2098 difference_type count = node->is_leaf() ? -begin.position_ : 0;
2099
2100 // First navigate to the leftmost leaf node past begin.
2101 if (node->is_internal()) {
2102 ++count;
2103 node = node->child(begin.position_ + 1);
2104 }
2105 while (node->is_internal()) node = node->start_child();
2106
2107 // Use `size_type` because `pos` needs to be able to hold `kNodeSlots+1`,
2108 // which isn't guaranteed to be a valid `field_type`.
2109 size_type pos = node->position();
2110 const node_type *parent = node->parent();
2111 for (;;) {
2112 // In each iteration of the next loop, we count one leaf node and go right.
2113 assert(pos <= parent->finish());
2114 do {
2115 node = parent->child(static_cast<field_type>(pos));
2116 if (node->is_internal()) {
2117 // Navigate to the leftmost leaf under node.
2118 while (node->is_internal()) node = node->start_child();
2119 pos = node->position();
2120 parent = node->parent();
2121 }
2122 if (node == end.node_) return count + end.position_;
2123 if (parent == end.node_ && pos == static_cast<size_type>(end.position_))
2124 return count + node->count();
2125 // +1 is for the next internal node value.
2126 count += node->count() + 1;
2127 ++pos;
2128 } while (pos <= parent->finish());
2129
2130 // Once we've counted all children of parent, go up/right.
2131 assert(pos > parent->finish());
2132 do {
2133 node = parent;
2134 pos = node->position();
2135 parent = node->parent();
2136 // -1 because we counted the value at end and shouldn't.
2137 if (parent == end.node_ && pos == static_cast<size_type>(end.position_))
2138 return count - 1;
2139 ++pos;
2140 } while (pos > parent->finish());
2141 }
2142 }
2143
2144 template <typename N, typename R, typename P>
2145 void btree_iterator<N, R, P>::increment_slow() {
2146 if (node_->is_leaf()) {
2147 assert(position_ >= node_->finish());
2148 btree_iterator save(*this);
2149 while (position_ == node_->finish() && !node_->is_root()) {
2150 assert(node_->parent()->child(node_->position()) == node_);
2151 position_ = node_->position();
2152 node_ = node_->parent();
2153 }
2154 // TODO(ezb): assert we aren't incrementing end() instead of handling.
2155 if (position_ == node_->finish()) {
2156 *this = save;
2157 }
2158 } else {
2159 assert(position_ < node_->finish());
2160 node_ = node_->child(static_cast<field_type>(position_ + 1));
2161 while (node_->is_internal()) {
2162 node_ = node_->start_child();
2163 }
2164 position_ = node_->start();
2165 }
2166 }
2167
2168 template <typename N, typename R, typename P>
2169 void btree_iterator<N, R, P>::decrement_slow() {
2170 if (node_->is_leaf()) {
2171 assert(position_ <= -1);
2172 btree_iterator save(*this);
2173 while (position_ < node_->start() && !node_->is_root()) {
2174 assert(node_->parent()->child(node_->position()) == node_);
2175 position_ = node_->position() - 1;
2176 node_ = node_->parent();
2177 }
2178 // TODO(ezb): assert we aren't decrementing begin() instead of handling.
2179 if (position_ < node_->start()) {
2180 *this = save;
2181 }
2182 } else {
2183 assert(position_ >= node_->start());
2184 node_ = node_->child(static_cast<field_type>(position_));
2185 while (node_->is_internal()) {
2186 node_ = node_->child(node_->finish());
2187 }
2188 position_ = node_->finish() - 1;
2189 }
2190 }
2191
2192 ////
2193 // btree methods
2194 template <typename P>
2195 template <typename Btree>
2196 void btree<P>::copy_or_move_values_in_order(Btree &other) {
2197 static_assert(std::is_same<btree, Btree>::value ||
2198 std::is_same<const btree, Btree>::value,
2199 "Btree type must be same or const.");
2200 assert(empty());
2201
2202 // We can avoid key comparisons because we know the order of the
2203 // values is the same order we'll store them in.
2204 auto iter = other.begin();
2205 if (iter == other.end()) return;
2206 insert_multi(iter.slot());
2207 ++iter;
2208 for (; iter != other.end(); ++iter) {
2209 // If the btree is not empty, we can just insert the new value at the end
2210 // of the tree.
2211 internal_emplace(end(), iter.slot());
2212 }
2213 }
2214
2215 template <typename P>
2216 constexpr bool btree<P>::static_assert_validation() {
2217 static_assert(std::is_nothrow_copy_constructible<key_compare>::value,
2218 "Key comparison must be nothrow copy constructible");
2219 static_assert(std::is_nothrow_copy_constructible<allocator_type>::value,
2220 "Allocator must be nothrow copy constructible");
2221 static_assert(std::is_trivially_copyable<iterator>::value,
2222 "iterator not trivially copyable.");
2223
2224 // Note: We assert that kTargetValues, which is computed from
2225 // Params::kTargetNodeSize, must fit the node_type::field_type.
2226 static_assert(
2227 kNodeSlots < (1 << (8 * sizeof(typename node_type::field_type))),
2228 "target node size too large");
2229
2230 // Verify that key_compare returns an absl::{weak,strong}_ordering or bool.
2231 static_assert(
2232 compare_has_valid_result_type<key_compare, key_type>(),
2233 "key comparison function must return absl::{weak,strong}_ordering or "
2234 "bool.");
2235
2236 // Test the assumption made in setting kNodeSlotSpace.
2237 static_assert(node_type::MinimumOverhead() >= sizeof(void *) + 4,
2238 "node space assumption incorrect");
2239
2240 return true;
2241 }
2242
2243 template <typename P>
2244 template <typename K>
2245 auto btree<P>::lower_bound_equal(const K &key) const
2246 -> std::pair<iterator, bool> {
2247 const SearchResult<iterator, is_key_compare_to::value> res =
2248 internal_lower_bound(key);
2249 const iterator lower = iterator(internal_end(res.value));
2250 const bool equal = res.HasMatch()
2251 ? res.IsEq()
2252 : lower != end() && !compare_keys(key, lower.key());
2253 return {lower, equal};
2254 }
2255
2256 template <typename P>
2257 template <typename K>
2258 auto btree<P>::equal_range(const K &key) -> std::pair<iterator, iterator> {
2259 const std::pair<iterator, bool> lower_and_equal = lower_bound_equal(key);
2260 const iterator lower = lower_and_equal.first;
2261 if (!lower_and_equal.second) {
2262 return {lower, lower};
2263 }
2264
2265 const iterator next = std::next(lower);
2266 if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
2267 // The next iterator after lower must point to a key greater than `key`.
2268 // Note: if this assert fails, then it may indicate that the comparator does
2269 // not meet the equivalence requirements for Compare
2270 // (see https://en.cppreference.com/w/cpp/named_req/Compare).
2271 assert(next == end() || compare_keys(key, next.key()));
2272 return {lower, next};
2273 }
2274 // Try once more to avoid the call to upper_bound() if there's only one
2275 // equivalent key. This should prevent all calls to upper_bound() in cases of
2276 // unique-containers with heterogeneous comparators in which all comparison
2277 // operators have the same equivalence classes.
2278 if (next == end() || compare_keys(key, next.key())) return {lower, next};
2279
2280 // In this case, we need to call upper_bound() to avoid worst case O(N)
2281 // behavior if we were to iterate over equal keys.
2282 return {lower, upper_bound(key)};
2283 }
2284
2285 template <typename P>
2286 template <typename K, typename... Args>
2287 auto btree<P>::insert_unique(const K &key, Args &&...args)
2288 -> std::pair<iterator, bool> {
2289 if (empty()) {
2290 mutable_root() = mutable_rightmost() = new_leaf_root_node(1);
2291 }
2292
2293 SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
2294 iterator iter = res.value;
2295
2296 if (res.HasMatch()) {
2297 if (res.IsEq()) {
2298 // The key already exists in the tree, do nothing.
2299 return {iter, false};
2300 }
2301 } else {
2302 iterator last = internal_last(iter);
2303 if (last.node_ && !compare_keys(key, last.key())) {
2304 // The key already exists in the tree, do nothing.
2305 return {last, false};
2306 }
2307 }
2308 return {internal_emplace(iter, std::forward<Args>(args)...), true};
2309 }
2310
2311 template <typename P>
2312 template <typename K, typename... Args>
2313 inline auto btree<P>::insert_hint_unique(iterator position, const K &key,
2314 Args &&...args)
2315 -> std::pair<iterator, bool> {
2316 if (!empty()) {
2317 if (position == end() || compare_keys(key, position.key())) {
2318 if (position == begin() || compare_keys(std::prev(position).key(), key)) {
2319 // prev.key() < key < position.key()
2320 return {internal_emplace(position, std::forward<Args>(args)...), true};
2321 }
2322 } else if (compare_keys(position.key(), key)) {
2323 ++position;
2324 if (position == end() || compare_keys(key, position.key())) {
2325 // {original `position`}.key() < key < {current `position`}.key()
2326 return {internal_emplace(position, std::forward<Args>(args)...), true};
2327 }
2328 } else {
2329 // position.key() == key
2330 return {position, false};
2331 }
2332 }
2333 return insert_unique(key, std::forward<Args>(args)...);
2334 }
2335
2336 template <typename P>
2337 template <typename InputIterator, typename>
2338 void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, int) {
2339 for (; b != e; ++b) {
2340 insert_hint_unique(end(), params_type::key(*b), *b);
2341 }
2342 }
2343
2344 template <typename P>
2345 template <typename InputIterator>
2346 void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, char) {
2347 for (; b != e; ++b) {
2348 // Use a node handle to manage a temp slot.
2349 auto node_handle =
2350 CommonAccess::Construct<node_handle_type>(get_allocator(), *b);
2351 slot_type *slot = CommonAccess::GetSlot(node_handle);
2352 insert_hint_unique(end(), params_type::key(slot), slot);
2353 }
2354 }
2355
2356 template <typename P>
2357 template <typename ValueType>
2358 auto btree<P>::insert_multi(const key_type &key, ValueType &&v) -> iterator {
2359 if (empty()) {
2360 mutable_root() = mutable_rightmost() = new_leaf_root_node(1);
2361 }
2362
2363 iterator iter = internal_upper_bound(key);
2364 if (iter.node_ == nullptr) {
2365 iter = end();
2366 }
2367 return internal_emplace(iter, std::forward<ValueType>(v));
2368 }
2369
2370 template <typename P>
2371 template <typename ValueType>
2372 auto btree<P>::insert_hint_multi(iterator position, ValueType &&v) -> iterator {
2373 if (!empty()) {
2374 const key_type &key = params_type::key(v);
2375 if (position == end() || !compare_keys(position.key(), key)) {
2376 if (position == begin() ||
2377 !compare_keys(key, std::prev(position).key())) {
2378 // prev.key() <= key <= position.key()
2379 return internal_emplace(position, std::forward<ValueType>(v));
2380 }
2381 } else {
2382 ++position;
2383 if (position == end() || !compare_keys(position.key(), key)) {
2384 // {original `position`}.key() < key < {current `position`}.key()
2385 return internal_emplace(position, std::forward<ValueType>(v));
2386 }
2387 }
2388 }
2389 return insert_multi(std::forward<ValueType>(v));
2390 }
2391
2392 template <typename P>
2393 template <typename InputIterator>
2394 void btree<P>::insert_iterator_multi(InputIterator b, InputIterator e) {
2395 for (; b != e; ++b) {
2396 insert_hint_multi(end(), *b);
2397 }
2398 }
2399
2400 template <typename P>
2401 auto btree<P>::operator=(const btree &other) -> btree & {
2402 if (this != &other) {
2403 clear();
2404
2405 *mutable_key_comp() = other.key_comp();
2406 if (absl::allocator_traits<
2407 allocator_type>::propagate_on_container_copy_assignment::value) {
2408 *mutable_allocator() = other.allocator();
2409 }
2410
2411 copy_or_move_values_in_order(other);
2412 }
2413 return *this;
2414 }
2415
2416 template <typename P>
2417 auto btree<P>::operator=(btree &&other) noexcept -> btree & {
2418 if (this != &other) {
2419 clear();
2420
2421 using std::swap;
2422 if (absl::allocator_traits<
2423 allocator_type>::propagate_on_container_copy_assignment::value) {
2424 swap(root_, other.root_);
2425 // Note: `rightmost_` also contains the allocator and the key comparator.
2426 swap(rightmost_, other.rightmost_);
2427 swap(size_, other.size_);
2428 } else {
2429 if (allocator() == other.allocator()) {
2430 swap(mutable_root(), other.mutable_root());
2431 swap(*mutable_key_comp(), *other.mutable_key_comp());
2432 swap(mutable_rightmost(), other.mutable_rightmost());
2433 swap(size_, other.size_);
2434 } else {
2435 // We aren't allowed to propagate the allocator and the allocator is
2436 // different so we can't take over its memory. We must move each element
2437 // individually. We need both `other` and `this` to have `other`s key
2438 // comparator while moving the values so we can't swap the key
2439 // comparators.
2440 *mutable_key_comp() = other.key_comp();
2441 copy_or_move_values_in_order(other);
2442 }
2443 }
2444 }
2445 return *this;
2446 }
2447
2448 template <typename P>
2449 auto btree<P>::erase(iterator iter) -> iterator {
2450 iter.node_->value_destroy(static_cast<field_type>(iter.position_),
2451 mutable_allocator());
2452 iter.update_generation();
2453
2454 const bool internal_delete = iter.node_->is_internal();
2455 if (internal_delete) {
2456 // Deletion of a value on an internal node. First, transfer the largest
2457 // value from our left child here, then erase/rebalance from that position.
2458 // We can get to the largest value from our left child by decrementing iter.
2459 iterator internal_iter(iter);
2460 --iter;
2461 assert(iter.node_->is_leaf());
2462 internal_iter.node_->transfer(
2463 static_cast<size_type>(internal_iter.position_),
2464 static_cast<size_type>(iter.position_), iter.node_,
2465 mutable_allocator());
2466 } else {
2467 // Shift values after erased position in leaf. In the internal case, we
2468 // don't need to do this because the leaf position is the end of the node.
2469 const field_type transfer_from =
2470 static_cast<field_type>(iter.position_ + 1);
2471 const field_type num_to_transfer = iter.node_->finish() - transfer_from;
2472 iter.node_->transfer_n(num_to_transfer,
2473 static_cast<size_type>(iter.position_),
2474 transfer_from, iter.node_, mutable_allocator());
2475 }
2476 // Update node finish and container size.
2477 iter.node_->set_finish(iter.node_->finish() - 1);
2478 --size_;
2479
2480 // We want to return the next value after the one we just erased. If we
2481 // erased from an internal node (internal_delete == true), then the next
2482 // value is ++(++iter). If we erased from a leaf node (internal_delete ==
2483 // false) then the next value is ++iter. Note that ++iter may point to an
2484 // internal node and the value in the internal node may move to a leaf node
2485 // (iter.node_) when rebalancing is performed at the leaf level.
2486
2487 iterator res = rebalance_after_delete(iter);
2488
2489 // If we erased from an internal node, advance the iterator.
2490 if (internal_delete) {
2491 ++res;
2492 }
2493 return res;
2494 }
2495
2496 template <typename P>
2497 auto btree<P>::rebalance_after_delete(iterator iter) -> iterator {
2498 // Merge/rebalance as we walk back up the tree.
2499 iterator res(iter);
2500 bool first_iteration = true;
2501 for (;;) {
2502 if (iter.node_ == root()) {
2503 try_shrink();
2504 if (empty()) {
2505 return end();
2506 }
2507 break;
2508 }
2509 if (iter.node_->count() >= kMinNodeValues) {
2510 break;
2511 }
2512 bool merged = try_merge_or_rebalance(&iter);
2513 // On the first iteration, we should update `res` with `iter` because `res`
2514 // may have been invalidated.
2515 if (first_iteration) {
2516 res = iter;
2517 first_iteration = false;
2518 }
2519 if (!merged) {
2520 break;
2521 }
2522 iter.position_ = iter.node_->position();
2523 iter.node_ = iter.node_->parent();
2524 }
2525 res.update_generation();
2526
2527 // Adjust our return value. If we're pointing at the end of a node, advance
2528 // the iterator.
2529 if (res.position_ == res.node_->finish()) {
2530 res.position_ = res.node_->finish() - 1;
2531 ++res;
2532 }
2533
2534 return res;
2535 }
2536
2537 template <typename P>
2538 auto btree<P>::erase_range(iterator begin, iterator end)
2539 -> std::pair<size_type, iterator> {
2540 size_type count = static_cast<size_type>(end - begin);
2541 assert(count >= 0);
2542
2543 if (count == 0) {
2544 return {0, begin};
2545 }
2546
2547 if (static_cast<size_type>(count) == size_) {
2548 clear();
2549 return {count, this->end()};
2550 }
2551
2552 if (begin.node_ == end.node_) {
2553 assert(end.position_ > begin.position_);
2554 begin.node_->remove_values(
2555 static_cast<field_type>(begin.position_),
2556 static_cast<field_type>(end.position_ - begin.position_),
2557 mutable_allocator());
2558 size_ -= count;
2559 return {count, rebalance_after_delete(begin)};
2560 }
2561
2562 const size_type target_size = size_ - count;
2563 while (size_ > target_size) {
2564 if (begin.node_->is_leaf()) {
2565 const size_type remaining_to_erase = size_ - target_size;
2566 const size_type remaining_in_node =
2567 static_cast<size_type>(begin.node_->finish() - begin.position_);
2568 const field_type to_erase = static_cast<field_type>(
2569 (std::min)(remaining_to_erase, remaining_in_node));
2570 begin.node_->remove_values(static_cast<field_type>(begin.position_),
2571 to_erase, mutable_allocator());
2572 size_ -= to_erase;
2573 begin = rebalance_after_delete(begin);
2574 } else {
2575 begin = erase(begin);
2576 }
2577 }
2578 begin.update_generation();
2579 return {count, begin};
2580 }
2581
2582 template <typename P>
2583 void btree<P>::clear() {
2584 if (!empty()) {
2585 node_type::clear_and_delete(root(), mutable_allocator());
2586 }
2587 mutable_root() = mutable_rightmost() = EmptyNode();
2588 size_ = 0;
2589 }
2590
2591 template <typename P>
2592 void btree<P>::swap(btree &other) {
2593 using std::swap;
2594 if (absl::allocator_traits<
2595 allocator_type>::propagate_on_container_swap::value) {
2596 // Note: `rightmost_` also contains the allocator and the key comparator.
2597 swap(rightmost_, other.rightmost_);
2598 } else {
2599 // It's undefined behavior if the allocators are unequal here.
2600 assert(allocator() == other.allocator());
2601 swap(mutable_rightmost(), other.mutable_rightmost());
2602 swap(*mutable_key_comp(), *other.mutable_key_comp());
2603 }
2604 swap(mutable_root(), other.mutable_root());
2605 swap(size_, other.size_);
2606 }
2607
2608 template <typename P>
2609 void btree<P>::verify() const {
2610 assert(root() != nullptr);
2611 assert(leftmost() != nullptr);
2612 assert(rightmost() != nullptr);
2613 assert(empty() || size() == internal_verify(root(), nullptr, nullptr));
2614 assert(leftmost() == (++const_iterator(root(), -1)).node_);
2615 assert(rightmost() == (--const_iterator(root(), root()->finish())).node_);
2616 assert(leftmost()->is_leaf());
2617 assert(rightmost()->is_leaf());
2618 }
2619
2620 template <typename P>
2621 void btree<P>::rebalance_or_split(iterator *iter) {
2622 node_type *&node = iter->node_;
2623 int &insert_position = iter->position_;
2624 assert(node->count() == node->max_count());
2625 assert(kNodeSlots == node->max_count());
2626
2627 // First try to make room on the node by rebalancing.
2628 node_type *parent = node->parent();
2629 if (node != root()) {
2630 if (node->position() > parent->start()) {
2631 // Try rebalancing with our left sibling.
2632 node_type *left = parent->child(node->position() - 1);
2633 assert(left->max_count() == kNodeSlots);
2634 if (left->count() < kNodeSlots) {
2635 // We bias rebalancing based on the position being inserted. If we're
2636 // inserting at the end of the right node then we bias rebalancing to
2637 // fill up the left node.
2638 field_type to_move =
2639 (kNodeSlots - left->count()) /
2640 (1 + (static_cast<field_type>(insert_position) < kNodeSlots));
2641 to_move = (std::max)(field_type{1}, to_move);
2642
2643 if (static_cast<field_type>(insert_position) - to_move >=
2644 node->start() ||
2645 left->count() + to_move < kNodeSlots) {
2646 left->rebalance_right_to_left(to_move, node, mutable_allocator());
2647
2648 assert(node->max_count() - node->count() == to_move);
2649 insert_position = static_cast<int>(
2650 static_cast<field_type>(insert_position) - to_move);
2651 if (insert_position < node->start()) {
2652 insert_position = insert_position + left->count() + 1;
2653 node = left;
2654 }
2655
2656 assert(node->count() < node->max_count());
2657 return;
2658 }
2659 }
2660 }
2661
2662 if (node->position() < parent->finish()) {
2663 // Try rebalancing with our right sibling.
2664 node_type *right = parent->child(node->position() + 1);
2665 assert(right->max_count() == kNodeSlots);
2666 if (right->count() < kNodeSlots) {
2667 // We bias rebalancing based on the position being inserted. If we're
2668 // inserting at the beginning of the left node then we bias rebalancing
2669 // to fill up the right node.
2670 field_type to_move = (kNodeSlots - right->count()) /
2671 (1 + (insert_position > node->start()));
2672 to_move = (std::max)(field_type{1}, to_move);
2673
2674 if (static_cast<field_type>(insert_position) <=
2675 node->finish() - to_move ||
2676 right->count() + to_move < kNodeSlots) {
2677 node->rebalance_left_to_right(to_move, right, mutable_allocator());
2678
2679 if (insert_position > node->finish()) {
2680 insert_position = insert_position - node->count() - 1;
2681 node = right;
2682 }
2683
2684 assert(node->count() < node->max_count());
2685 return;
2686 }
2687 }
2688 }
2689
2690 // Rebalancing failed, make sure there is room on the parent node for a new
2691 // value.
2692 assert(parent->max_count() == kNodeSlots);
2693 if (parent->count() == kNodeSlots) {
2694 iterator parent_iter(parent, node->position());
2695 rebalance_or_split(&parent_iter);
2696 parent = node->parent();
2697 }
2698 } else {
2699 // Rebalancing not possible because this is the root node.
2700 // Create a new root node and set the current root node as the child of the
2701 // new root.
2702 parent = new_internal_node(/*position=*/0, parent);
2703 parent->set_generation(root()->generation());
2704 parent->init_child(parent->start(), node);
2705 mutable_root() = parent;
2706 // If the former root was a leaf node, then it's now the rightmost node.
2707 assert(parent->start_child()->is_internal() ||
2708 parent->start_child() == rightmost());
2709 }
2710
2711 // Split the node.
2712 node_type *split_node;
2713 if (node->is_leaf()) {
2714 split_node = new_leaf_node(node->position() + 1, parent);
2715 node->split(insert_position, split_node, mutable_allocator());
2716 if (rightmost() == node) mutable_rightmost() = split_node;
2717 } else {
2718 split_node = new_internal_node(node->position() + 1, parent);
2719 node->split(insert_position, split_node, mutable_allocator());
2720 }
2721
2722 if (insert_position > node->finish()) {
2723 insert_position = insert_position - node->count() - 1;
2724 node = split_node;
2725 }
2726 }
2727
2728 template <typename P>
2729 void btree<P>::merge_nodes(node_type *left, node_type *right) {
2730 left->merge(right, mutable_allocator());
2731 if (rightmost() == right) mutable_rightmost() = left;
2732 }
2733
2734 template <typename P>
2735 bool btree<P>::try_merge_or_rebalance(iterator *iter) {
2736 node_type *parent = iter->node_->parent();
2737 if (iter->node_->position() > parent->start()) {
2738 // Try merging with our left sibling.
2739 node_type *left = parent->child(iter->node_->position() - 1);
2740 assert(left->max_count() == kNodeSlots);
2741 if (1U + left->count() + iter->node_->count() <= kNodeSlots) {
2742 iter->position_ += 1 + left->count();
2743 merge_nodes(left, iter->node_);
2744 iter->node_ = left;
2745 return true;
2746 }
2747 }
2748 if (iter->node_->position() < parent->finish()) {
2749 // Try merging with our right sibling.
2750 node_type *right = parent->child(iter->node_->position() + 1);
2751 assert(right->max_count() == kNodeSlots);
2752 if (1U + iter->node_->count() + right->count() <= kNodeSlots) {
2753 merge_nodes(iter->node_, right);
2754 return true;
2755 }
2756 // Try rebalancing with our right sibling. We don't perform rebalancing if
2757 // we deleted the first element from iter->node_ and the node is not
2758 // empty. This is a small optimization for the common pattern of deleting
2759 // from the front of the tree.
2760 if (right->count() > kMinNodeValues &&
2761 (iter->node_->count() == 0 || iter->position_ > iter->node_->start())) {
2762 field_type to_move = (right->count() - iter->node_->count()) / 2;
2763 to_move =
2764 (std::min)(to_move, static_cast<field_type>(right->count() - 1));
2765 iter->node_->rebalance_right_to_left(to_move, right, mutable_allocator());
2766 return false;
2767 }
2768 }
2769 if (iter->node_->position() > parent->start()) {
2770 // Try rebalancing with our left sibling. We don't perform rebalancing if
2771 // we deleted the last element from iter->node_ and the node is not
2772 // empty. This is a small optimization for the common pattern of deleting
2773 // from the back of the tree.
2774 node_type *left = parent->child(iter->node_->position() - 1);
2775 if (left->count() > kMinNodeValues &&
2776 (iter->node_->count() == 0 ||
2777 iter->position_ < iter->node_->finish())) {
2778 field_type to_move = (left->count() - iter->node_->count()) / 2;
2779 to_move = (std::min)(to_move, static_cast<field_type>(left->count() - 1));
2780 left->rebalance_left_to_right(to_move, iter->node_, mutable_allocator());
2781 iter->position_ += to_move;
2782 return false;
2783 }
2784 }
2785 return false;
2786 }
2787
2788 template <typename P>
2789 void btree<P>::try_shrink() {
2790 node_type *orig_root = root();
2791 if (orig_root->count() > 0) {
2792 return;
2793 }
2794 // Deleted the last item on the root node, shrink the height of the tree.
2795 if (orig_root->is_leaf()) {
2796 assert(size() == 0);
2797 mutable_root() = mutable_rightmost() = EmptyNode();
2798 } else {
2799 node_type *child = orig_root->start_child();
2800 child->make_root();
2801 mutable_root() = child;
2802 }
2803 node_type::clear_and_delete(orig_root, mutable_allocator());
2804 }
2805
2806 template <typename P>
2807 template <typename IterType>
2808 inline IterType btree<P>::internal_last(IterType iter) {
2809 assert(iter.node_ != nullptr);
2810 while (iter.position_ == iter.node_->finish()) {
2811 iter.position_ = iter.node_->position();
2812 iter.node_ = iter.node_->parent();
2813 if (iter.node_->is_leaf()) {
2814 iter.node_ = nullptr;
2815 break;
2816 }
2817 }
2818 iter.update_generation();
2819 return iter;
2820 }
2821
2822 template <typename P>
2823 template <typename... Args>
2824 inline auto btree<P>::internal_emplace(iterator iter, Args &&...args)
2825 -> iterator {
2826 if (iter.node_->is_internal()) {
2827 // We can't insert on an internal node. Instead, we'll insert after the
2828 // previous value which is guaranteed to be on a leaf node.
2829 --iter;
2830 ++iter.position_;
2831 }
2832 const field_type max_count = iter.node_->max_count();
2833 allocator_type *alloc = mutable_allocator();
2834
2835 const auto transfer_and_delete = [&](node_type *old_node,
2836 node_type *new_node) {
2837 new_node->transfer_n(old_node->count(), new_node->start(),
2838 old_node->start(), old_node, alloc);
2839 new_node->set_finish(old_node->finish());
2840 old_node->set_finish(old_node->start());
2841 new_node->set_generation(old_node->generation());
2842 node_type::clear_and_delete(old_node, alloc);
2843 };
2844 const auto replace_leaf_root_node = [&](field_type new_node_size) {
2845 assert(iter.node_ == root());
2846 node_type *old_root = iter.node_;
2847 node_type *new_root = iter.node_ = new_leaf_root_node(new_node_size);
2848 transfer_and_delete(old_root, new_root);
2849 mutable_root() = mutable_rightmost() = new_root;
2850 };
2851
2852 bool replaced_node = false;
2853 if (iter.node_->count() == max_count) {
2854 // Make room in the leaf for the new item.
2855 if (max_count < kNodeSlots) {
2856 // Insertion into the root where the root is smaller than the full node
2857 // size. Simply grow the size of the root node.
2858 replace_leaf_root_node(static_cast<field_type>(
2859 (std::min)(static_cast<int>(kNodeSlots), 2 * max_count)));
2860 replaced_node = true;
2861 } else {
2862 rebalance_or_split(&iter);
2863 }
2864 }
2865 (void)replaced_node;
2866 #ifdef ABSL_HAVE_ADDRESS_SANITIZER
2867 if (!replaced_node) {
2868 assert(iter.node_->is_leaf());
2869 if (iter.node_->is_root()) {
2870 replace_leaf_root_node(max_count);
2871 } else {
2872 node_type *old_node = iter.node_;
2873 const bool was_rightmost = rightmost() == old_node;
2874 const bool was_leftmost = leftmost() == old_node;
2875 node_type *parent = old_node->parent();
2876 const field_type position = old_node->position();
2877 node_type *new_node = iter.node_ = new_leaf_node(position, parent);
2878 parent->set_child_noupdate_position(position, new_node);
2879 transfer_and_delete(old_node, new_node);
2880 if (was_rightmost) mutable_rightmost() = new_node;
2881 // The leftmost node is stored as the parent of the root node.
2882 if (was_leftmost) root()->set_parent(new_node);
2883 }
2884 }
2885 #endif
2886 iter.node_->emplace_value(static_cast<field_type>(iter.position_), alloc,
2887 std::forward<Args>(args)...);
2888 assert(
2889 iter.node_->is_ordered_correctly(static_cast<field_type>(iter.position_),
2890 original_key_compare(key_comp())) &&
2891 "If this assert fails, then either (1) the comparator may violate "
2892 "transitivity, i.e. comp(a,b) && comp(b,c) -> comp(a,c) (see "
2893 "https://en.cppreference.com/w/cpp/named_req/Compare), or (2) a "
2894 "key may have been mutated after it was inserted into the tree.");
2895 ++size_;
2896 iter.update_generation();
2897 return iter;
2898 }
2899
2900 template <typename P>
2901 template <typename K>
2902 inline auto btree<P>::internal_locate(const K &key) const
2903 -> SearchResult<iterator, is_key_compare_to::value> {
2904 iterator iter(const_cast<node_type *>(root()));
2905 for (;;) {
2906 SearchResult<size_type, is_key_compare_to::value> res =
2907 iter.node_->lower_bound(key, key_comp());
2908 iter.position_ = static_cast<int>(res.value);
2909 if (res.IsEq()) {
2910 return {iter, MatchKind::kEq};
2911 }
2912 // Note: in the non-key-compare-to case, we don't need to walk all the way
2913 // down the tree if the keys are equal, but determining equality would
2914 // require doing an extra comparison on each node on the way down, and we
2915 // will need to go all the way to the leaf node in the expected case.
2916 if (iter.node_->is_leaf()) {
2917 break;
2918 }
2919 iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
2920 }
2921 // Note: in the non-key-compare-to case, the key may actually be equivalent
2922 // here (and the MatchKind::kNe is ignored).
2923 return {iter, MatchKind::kNe};
2924 }
2925
2926 template <typename P>
2927 template <typename K>
2928 auto btree<P>::internal_lower_bound(const K &key) const
2929 -> SearchResult<iterator, is_key_compare_to::value> {
2930 if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
2931 SearchResult<iterator, is_key_compare_to::value> ret = internal_locate(key);
2932 ret.value = internal_last(ret.value);
2933 return ret;
2934 }
2935 iterator iter(const_cast<node_type *>(root()));
2936 SearchResult<size_type, is_key_compare_to::value> res;
2937 bool seen_eq = false;
2938 for (;;) {
2939 res = iter.node_->lower_bound(key, key_comp());
2940 iter.position_ = static_cast<int>(res.value);
2941 if (iter.node_->is_leaf()) {
2942 break;
2943 }
2944 seen_eq = seen_eq || res.IsEq();
2945 iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
2946 }
2947 if (res.IsEq()) return {iter, MatchKind::kEq};
2948 return {internal_last(iter), seen_eq ? MatchKind::kEq : MatchKind::kNe};
2949 }
2950
2951 template <typename P>
2952 template <typename K>
2953 auto btree<P>::internal_upper_bound(const K &key) const -> iterator {
2954 iterator iter(const_cast<node_type *>(root()));
2955 for (;;) {
2956 iter.position_ = static_cast<int>(iter.node_->upper_bound(key, key_comp()));
2957 if (iter.node_->is_leaf()) {
2958 break;
2959 }
2960 iter.node_ = iter.node_->child(static_cast<field_type>(iter.position_));
2961 }
2962 return internal_last(iter);
2963 }
2964
2965 template <typename P>
2966 template <typename K>
2967 auto btree<P>::internal_find(const K &key) const -> iterator {
2968 SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
2969 if (res.HasMatch()) {
2970 if (res.IsEq()) {
2971 return res.value;
2972 }
2973 } else {
2974 const iterator iter = internal_last(res.value);
2975 if (iter.node_ != nullptr && !compare_keys(key, iter.key())) {
2976 return iter;
2977 }
2978 }
2979 return {nullptr, 0};
2980 }
2981
2982 template <typename P>
2983 typename btree<P>::size_type btree<P>::internal_verify(
2984 const node_type *node, const key_type *lo, const key_type *hi) const {
2985 assert(node->count() > 0);
2986 assert(node->count() <= node->max_count());
2987 if (lo) {
2988 assert(!compare_keys(node->key(node->start()), *lo));
2989 }
2990 if (hi) {
2991 assert(!compare_keys(*hi, node->key(node->finish() - 1)));
2992 }
2993 for (int i = node->start() + 1; i < node->finish(); ++i) {
2994 assert(!compare_keys(node->key(i), node->key(i - 1)));
2995 }
2996 size_type count = node->count();
2997 if (node->is_internal()) {
2998 for (field_type i = node->start(); i <= node->finish(); ++i) {
2999 assert(node->child(i) != nullptr);
3000 assert(node->child(i)->parent() == node);
3001 assert(node->child(i)->position() == i);
3002 count += internal_verify(node->child(i),
3003 i == node->start() ? lo : &node->key(i - 1),
3004 i == node->finish() ? hi : &node->key(i));
3005 }
3006 }
3007 return count;
3008 }
3009
3010 struct btree_access {
3011 template <typename BtreeContainer, typename Pred>
3012 static auto erase_if(BtreeContainer &container, Pred pred) ->
3013 typename BtreeContainer::size_type {
3014 const auto initial_size = container.size();
3015 auto &tree = container.tree_;
3016 auto *alloc = tree.mutable_allocator();
3017 for (auto it = container.begin(); it != container.end();) {
3018 if (!pred(*it)) {
3019 ++it;
3020 continue;
3021 }
3022 auto *node = it.node_;
3023 if (node->is_internal()) {
3024 // Handle internal nodes normally.
3025 it = container.erase(it);
3026 continue;
3027 }
3028 // If this is a leaf node, then we do all the erases from this node
3029 // at once before doing rebalancing.
3030
3031 // The current position to transfer slots to.
3032 int to_pos = it.position_;
3033 node->value_destroy(it.position_, alloc);
3034 while (++it.position_ < node->finish()) {
3035 it.update_generation();
3036 if (pred(*it)) {
3037 node->value_destroy(it.position_, alloc);
3038 } else {
3039 node->transfer(node->slot(to_pos++), node->slot(it.position_), alloc);
3040 }
3041 }
3042 const int num_deleted = node->finish() - to_pos;
3043 tree.size_ -= num_deleted;
3044 node->set_finish(to_pos);
3045 it.position_ = to_pos;
3046 it = tree.rebalance_after_delete(it);
3047 }
3048 return initial_size - container.size();
3049 }
3050 };
3051
3052 #undef ABSL_BTREE_ENABLE_GENERATIONS
3053
3054 } // namespace container_internal
3055 ABSL_NAMESPACE_END
3056 } // namespace absl
3057
3058 #endif // ABSL_CONTAINER_INTERNAL_BTREE_H_
3059