blob: 6f5f01b86ae5870cf3b90e32fc2caaca2b6a106e [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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/macros.h"
62#include "absl/container/internal/common.h"
63#include "absl/container/internal/compressed_tuple.h"
64#include "absl/container/internal/container_memory.h"
65#include "absl/container/internal/layout.h"
66#include "absl/memory/memory.h"
67#include "absl/meta/type_traits.h"
Austin Schuhb4691e92020-12-31 12:37:18 -080068#include "absl/strings/cord.h"
Austin Schuh36244a12019-09-21 17:52:38 -070069#include "absl/strings/string_view.h"
70#include "absl/types/compare.h"
71#include "absl/utility/utility.h"
72
73namespace absl {
Austin Schuhb4691e92020-12-31 12:37:18 -080074ABSL_NAMESPACE_BEGIN
Austin Schuh36244a12019-09-21 17:52:38 -070075namespace container_internal {
76
77// A helper class that indicates if the Compare parameter is a key-compare-to
78// comparator.
79template <typename Compare, typename T>
80using btree_is_key_compare_to =
81 std::is_convertible<absl::result_of_t<Compare(const T &, const T &)>,
82 absl::weak_ordering>;
83
84struct StringBtreeDefaultLess {
85 using is_transparent = void;
86
87 StringBtreeDefaultLess() = default;
88
89 // Compatibility constructor.
90 StringBtreeDefaultLess(std::less<std::string>) {} // NOLINT
91 StringBtreeDefaultLess(std::less<string_view>) {} // NOLINT
92
93 absl::weak_ordering operator()(absl::string_view lhs,
94 absl::string_view rhs) const {
95 return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
96 }
Austin Schuhb4691e92020-12-31 12:37:18 -080097 StringBtreeDefaultLess(std::less<absl::Cord>) {} // NOLINT
98 absl::weak_ordering operator()(const absl::Cord &lhs,
99 const absl::Cord &rhs) const {
100 return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
101 }
102 absl::weak_ordering operator()(const absl::Cord &lhs,
103 absl::string_view rhs) const {
104 return compare_internal::compare_result_as_ordering(lhs.Compare(rhs));
105 }
106 absl::weak_ordering operator()(absl::string_view lhs,
107 const absl::Cord &rhs) const {
108 return compare_internal::compare_result_as_ordering(-rhs.Compare(lhs));
109 }
Austin Schuh36244a12019-09-21 17:52:38 -0700110};
111
112struct StringBtreeDefaultGreater {
113 using is_transparent = void;
114
115 StringBtreeDefaultGreater() = default;
116
117 StringBtreeDefaultGreater(std::greater<std::string>) {} // NOLINT
118 StringBtreeDefaultGreater(std::greater<string_view>) {} // NOLINT
119
120 absl::weak_ordering operator()(absl::string_view lhs,
121 absl::string_view rhs) const {
122 return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
123 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800124 StringBtreeDefaultGreater(std::greater<absl::Cord>) {} // NOLINT
125 absl::weak_ordering operator()(const absl::Cord &lhs,
126 const absl::Cord &rhs) const {
127 return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
128 }
129 absl::weak_ordering operator()(const absl::Cord &lhs,
130 absl::string_view rhs) const {
131 return compare_internal::compare_result_as_ordering(-lhs.Compare(rhs));
132 }
133 absl::weak_ordering operator()(absl::string_view lhs,
134 const absl::Cord &rhs) const {
135 return compare_internal::compare_result_as_ordering(rhs.Compare(lhs));
136 }
Austin Schuh36244a12019-09-21 17:52:38 -0700137};
138
139// A helper class to convert a boolean comparison into a three-way "compare-to"
Austin Schuhb4691e92020-12-31 12:37:18 -0800140// comparison that returns an `absl::weak_ordering`. This helper
Austin Schuh36244a12019-09-21 17:52:38 -0700141// class is specialized for less<std::string>, greater<std::string>,
Austin Schuhb4691e92020-12-31 12:37:18 -0800142// less<string_view>, greater<string_view>, less<absl::Cord>, and
143// greater<absl::Cord>.
Austin Schuh36244a12019-09-21 17:52:38 -0700144//
145// key_compare_to_adapter is provided so that btree users
146// automatically get the more efficient compare-to code when using common
Austin Schuhb4691e92020-12-31 12:37:18 -0800147// Abseil string types with common comparison functors.
Austin Schuh36244a12019-09-21 17:52:38 -0700148// These string-like specializations also turn on heterogeneous lookup by
149// default.
150template <typename Compare>
151struct key_compare_to_adapter {
152 using type = Compare;
153};
154
155template <>
156struct key_compare_to_adapter<std::less<std::string>> {
157 using type = StringBtreeDefaultLess;
158};
159
160template <>
161struct key_compare_to_adapter<std::greater<std::string>> {
162 using type = StringBtreeDefaultGreater;
163};
164
165template <>
166struct key_compare_to_adapter<std::less<absl::string_view>> {
167 using type = StringBtreeDefaultLess;
168};
169
170template <>
171struct key_compare_to_adapter<std::greater<absl::string_view>> {
172 using type = StringBtreeDefaultGreater;
173};
174
Austin Schuhb4691e92020-12-31 12:37:18 -0800175template <>
176struct key_compare_to_adapter<std::less<absl::Cord>> {
177 using type = StringBtreeDefaultLess;
178};
179
180template <>
181struct key_compare_to_adapter<std::greater<absl::Cord>> {
182 using type = StringBtreeDefaultGreater;
183};
184
185// Detects an 'absl_btree_prefer_linear_node_search' member. This is
186// a protocol used as an opt-in or opt-out of linear search.
187//
188// For example, this would be useful for key types that wrap an integer
189// and define their own cheap operator<(). For example:
190//
191// class K {
192// public:
193// using absl_btree_prefer_linear_node_search = std::true_type;
194// ...
195// private:
196// friend bool operator<(K a, K b) { return a.k_ < b.k_; }
197// int k_;
198// };
199//
200// btree_map<K, V> m; // Uses linear search
201//
202// If T has the preference tag, then it has a preference.
203// Btree will use the tag's truth value.
204template <typename T, typename = void>
205struct has_linear_node_search_preference : std::false_type {};
206template <typename T, typename = void>
207struct prefers_linear_node_search : std::false_type {};
208template <typename T>
209struct has_linear_node_search_preference<
210 T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
211 : std::true_type {};
212template <typename T>
213struct prefers_linear_node_search<
214 T, absl::void_t<typename T::absl_btree_prefer_linear_node_search>>
215 : T::absl_btree_prefer_linear_node_search {};
216
Austin Schuh36244a12019-09-21 17:52:38 -0700217template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
218 bool Multi, typename SlotPolicy>
219struct common_params {
Austin Schuhb4691e92020-12-31 12:37:18 -0800220 // If Compare is a common comparator for a string-like type, then we adapt it
Austin Schuh36244a12019-09-21 17:52:38 -0700221 // to use heterogeneous lookup and to be a key-compare-to comparator.
222 using key_compare = typename key_compare_to_adapter<Compare>::type;
223 // A type which indicates if we have a key-compare-to functor or a plain old
224 // key-compare functor.
225 using is_key_compare_to = btree_is_key_compare_to<key_compare, Key>;
226
227 using allocator_type = Alloc;
228 using key_type = Key;
229 using size_type = std::make_signed<size_t>::type;
230 using difference_type = ptrdiff_t;
231
Austin Schuh36244a12019-09-21 17:52:38 -0700232 using slot_policy = SlotPolicy;
233 using slot_type = typename slot_policy::slot_type;
234 using value_type = typename slot_policy::value_type;
235 using init_type = typename slot_policy::mutable_value_type;
236 using pointer = value_type *;
237 using const_pointer = const value_type *;
238 using reference = value_type &;
239 using const_reference = const value_type &;
240
Austin Schuhb4691e92020-12-31 12:37:18 -0800241 // For the given lookup key type, returns whether we can have multiple
242 // equivalent keys in the btree. If this is a multi-container, then we can.
243 // Otherwise, we can have multiple equivalent keys only if all of the
244 // following conditions are met:
245 // - The comparator is transparent.
246 // - The lookup key type is not the same as key_type.
247 // - The comparator is not a StringBtreeDefault{Less,Greater} comparator
248 // that we know has the same equivalence classes for all lookup types.
249 template <typename LookupKey>
250 constexpr static bool can_have_multiple_equivalent_keys() {
251 return Multi ||
252 (IsTransparent<key_compare>::value &&
253 !std::is_same<LookupKey, Key>::value &&
254 !std::is_same<key_compare, StringBtreeDefaultLess>::value &&
255 !std::is_same<key_compare, StringBtreeDefaultGreater>::value);
256 }
257
Austin Schuh36244a12019-09-21 17:52:38 -0700258 enum {
259 kTargetNodeSize = TargetNodeSize,
260
261 // Upper bound for the available space for values. This is largest for leaf
262 // nodes, which have overhead of at least a pointer + 4 bytes (for storing
263 // 3 field_types and an enum).
264 kNodeValueSpace =
265 TargetNodeSize - /*minimum overhead=*/(sizeof(void *) + 4),
266 };
267
268 // This is an integral type large enough to hold as many
269 // ValueSize-values as will fit a node of TargetNodeSize bytes.
270 using node_count_type =
271 absl::conditional_t<(kNodeValueSpace / sizeof(value_type) >
272 (std::numeric_limits<uint8_t>::max)()),
273 uint16_t, uint8_t>; // NOLINT
274
275 // The following methods are necessary for passing this struct as PolicyTraits
276 // for node_handle and/or are used within btree.
277 static value_type &element(slot_type *slot) {
278 return slot_policy::element(slot);
279 }
280 static const value_type &element(const slot_type *slot) {
281 return slot_policy::element(slot);
282 }
283 template <class... Args>
284 static void construct(Alloc *alloc, slot_type *slot, Args &&... args) {
285 slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
286 }
287 static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
288 slot_policy::construct(alloc, slot, other);
289 }
290 static void destroy(Alloc *alloc, slot_type *slot) {
291 slot_policy::destroy(alloc, slot);
292 }
293 static void transfer(Alloc *alloc, slot_type *new_slot, slot_type *old_slot) {
294 construct(alloc, new_slot, old_slot);
295 destroy(alloc, old_slot);
296 }
297 static void swap(Alloc *alloc, slot_type *a, slot_type *b) {
298 slot_policy::swap(alloc, a, b);
299 }
300 static void move(Alloc *alloc, slot_type *src, slot_type *dest) {
301 slot_policy::move(alloc, src, dest);
302 }
Austin Schuh36244a12019-09-21 17:52:38 -0700303};
304
305// A parameters structure for holding the type parameters for a btree_map.
306// Compare and Alloc should be nothrow copy-constructible.
307template <typename Key, typename Data, typename Compare, typename Alloc,
308 int TargetNodeSize, bool Multi>
309struct map_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
310 map_slot_policy<Key, Data>> {
311 using super_type = typename map_params::common_params;
312 using mapped_type = Data;
313 // This type allows us to move keys when it is safe to do so. It is safe
314 // for maps in which value_type and mutable_value_type are layout compatible.
315 using slot_policy = typename super_type::slot_policy;
316 using slot_type = typename super_type::slot_type;
317 using value_type = typename super_type::value_type;
318 using init_type = typename super_type::init_type;
319
320 using key_compare = typename super_type::key_compare;
321 // Inherit from key_compare for empty base class optimization.
322 struct value_compare : private key_compare {
323 value_compare() = default;
324 explicit value_compare(const key_compare &cmp) : key_compare(cmp) {}
325
326 template <typename T, typename U>
327 auto operator()(const T &left, const U &right) const
328 -> decltype(std::declval<key_compare>()(left.first, right.first)) {
329 return key_compare::operator()(left.first, right.first);
330 }
331 };
332 using is_map_container = std::true_type;
333
Austin Schuhb4691e92020-12-31 12:37:18 -0800334 template <typename V>
335 static auto key(const V &value) -> decltype(value.first) {
336 return value.first;
337 }
338 static const Key &key(const slot_type *s) { return slot_policy::key(s); }
339 static const Key &key(slot_type *s) { return slot_policy::key(s); }
340 // For use in node handle.
341 static auto mutable_key(slot_type *s)
342 -> decltype(slot_policy::mutable_key(s)) {
343 return slot_policy::mutable_key(s);
344 }
Austin Schuh36244a12019-09-21 17:52:38 -0700345 static mapped_type &value(value_type *value) { return value->second; }
346};
347
348// This type implements the necessary functions from the
349// absl::container_internal::slot_type interface.
350template <typename Key>
351struct set_slot_policy {
352 using slot_type = Key;
353 using value_type = Key;
354 using mutable_value_type = Key;
355
356 static value_type &element(slot_type *slot) { return *slot; }
357 static const value_type &element(const slot_type *slot) { return *slot; }
358
359 template <typename Alloc, class... Args>
360 static void construct(Alloc *alloc, slot_type *slot, Args &&... args) {
361 absl::allocator_traits<Alloc>::construct(*alloc, slot,
362 std::forward<Args>(args)...);
363 }
364
365 template <typename Alloc>
366 static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
367 absl::allocator_traits<Alloc>::construct(*alloc, slot, std::move(*other));
368 }
369
370 template <typename Alloc>
371 static void destroy(Alloc *alloc, slot_type *slot) {
372 absl::allocator_traits<Alloc>::destroy(*alloc, slot);
373 }
374
375 template <typename Alloc>
376 static void swap(Alloc * /*alloc*/, slot_type *a, slot_type *b) {
377 using std::swap;
378 swap(*a, *b);
379 }
380
381 template <typename Alloc>
382 static void move(Alloc * /*alloc*/, slot_type *src, slot_type *dest) {
383 *dest = std::move(*src);
384 }
Austin Schuh36244a12019-09-21 17:52:38 -0700385};
386
387// A parameters structure for holding the type parameters for a btree_set.
388// Compare and Alloc should be nothrow copy-constructible.
389template <typename Key, typename Compare, typename Alloc, int TargetNodeSize,
390 bool Multi>
391struct set_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
392 set_slot_policy<Key>> {
393 using value_type = Key;
394 using slot_type = typename set_params::common_params::slot_type;
395 using value_compare = typename set_params::common_params::key_compare;
396 using is_map_container = std::false_type;
397
Austin Schuhb4691e92020-12-31 12:37:18 -0800398 template <typename V>
399 static const V &key(const V &value) { return value; }
400 static const Key &key(const slot_type *slot) { return *slot; }
401 static const Key &key(slot_type *slot) { return *slot; }
Austin Schuh36244a12019-09-21 17:52:38 -0700402};
403
404// An adapter class that converts a lower-bound compare into an upper-bound
405// compare. Note: there is no need to make a version of this adapter specialized
406// for key-compare-to functors because the upper-bound (the first value greater
407// than the input) is never an exact match.
408template <typename Compare>
409struct upper_bound_adapter {
410 explicit upper_bound_adapter(const Compare &c) : comp(c) {}
Austin Schuhb4691e92020-12-31 12:37:18 -0800411 template <typename K1, typename K2>
412 bool operator()(const K1 &a, const K2 &b) const {
Austin Schuh36244a12019-09-21 17:52:38 -0700413 // Returns true when a is not greater than b.
414 return !compare_internal::compare_result_as_less_than(comp(b, a));
415 }
416
417 private:
418 Compare comp;
419};
420
421enum class MatchKind : uint8_t { kEq, kNe };
422
423template <typename V, bool IsCompareTo>
424struct SearchResult {
425 V value;
426 MatchKind match;
427
428 static constexpr bool HasMatch() { return true; }
429 bool IsEq() const { return match == MatchKind::kEq; }
430};
431
432// When we don't use CompareTo, `match` is not present.
433// This ensures that callers can't use it accidentally when it provides no
434// useful information.
435template <typename V>
436struct SearchResult<V, false> {
Austin Schuhb4691e92020-12-31 12:37:18 -0800437 SearchResult() {}
438 explicit SearchResult(V value) : value(value) {}
439 SearchResult(V value, MatchKind /*match*/) : value(value) {}
440
Austin Schuh36244a12019-09-21 17:52:38 -0700441 V value;
442
443 static constexpr bool HasMatch() { return false; }
444 static constexpr bool IsEq() { return false; }
445};
446
447// A node in the btree holding. The same node type is used for both internal
448// and leaf nodes in the btree, though the nodes are allocated in such a way
449// that the children array is only valid in internal nodes.
450template <typename Params>
451class btree_node {
452 using is_key_compare_to = typename Params::is_key_compare_to;
Austin Schuh36244a12019-09-21 17:52:38 -0700453 using field_type = typename Params::node_count_type;
454 using allocator_type = typename Params::allocator_type;
455 using slot_type = typename Params::slot_type;
456
457 public:
458 using params_type = Params;
459 using key_type = typename Params::key_type;
460 using value_type = typename Params::value_type;
461 using pointer = typename Params::pointer;
462 using const_pointer = typename Params::const_pointer;
463 using reference = typename Params::reference;
464 using const_reference = typename Params::const_reference;
465 using key_compare = typename Params::key_compare;
466 using size_type = typename Params::size_type;
467 using difference_type = typename Params::difference_type;
468
469 // Btree decides whether to use linear node search as follows:
Austin Schuhb4691e92020-12-31 12:37:18 -0800470 // - If the comparator expresses a preference, use that.
471 // - If the key expresses a preference, use that.
Austin Schuh36244a12019-09-21 17:52:38 -0700472 // - If the key is arithmetic and the comparator is std::less or
473 // std::greater, choose linear.
474 // - Otherwise, choose binary.
475 // TODO(ezb): Might make sense to add condition(s) based on node-size.
476 using use_linear_search = std::integral_constant<
477 bool,
Austin Schuhb4691e92020-12-31 12:37:18 -0800478 has_linear_node_search_preference<key_compare>::value
479 ? prefers_linear_node_search<key_compare>::value
480 : has_linear_node_search_preference<key_type>::value
481 ? prefers_linear_node_search<key_type>::value
482 : std::is_arithmetic<key_type>::value &&
483 (std::is_same<std::less<key_type>, key_compare>::value ||
484 std::is_same<std::greater<key_type>,
485 key_compare>::value)>;
Austin Schuh36244a12019-09-21 17:52:38 -0700486
487 // This class is organized by gtl::Layout as if it had the following
488 // structure:
489 // // A pointer to the node's parent.
490 // btree_node *parent;
491 //
492 // // The position of the node in the node's parent.
493 // field_type position;
494 // // The index of the first populated value in `values`.
495 // // TODO(ezb): right now, `start` is always 0. Update insertion/merge
496 // // logic to allow for floating storage within nodes.
497 // field_type start;
Austin Schuhb4691e92020-12-31 12:37:18 -0800498 // // The index after the last populated value in `values`. Currently, this
499 // // is the same as the count of values.
500 // field_type finish;
Austin Schuh36244a12019-09-21 17:52:38 -0700501 // // The maximum number of values the node can hold. This is an integer in
502 // // [1, kNodeValues] for root leaf nodes, kNodeValues for non-root leaf
503 // // nodes, and kInternalNodeMaxCount (as a sentinel value) for internal
504 // // nodes (even though there are still kNodeValues values in the node).
505 // // TODO(ezb): make max_count use only 4 bits and record log2(capacity)
506 // // to free extra bits for is_root, etc.
507 // field_type max_count;
508 //
509 // // The array of values. The capacity is `max_count` for leaf nodes and
510 // // kNodeValues for internal nodes. Only the values in
Austin Schuhb4691e92020-12-31 12:37:18 -0800511 // // [start, finish) have been initialized and are valid.
Austin Schuh36244a12019-09-21 17:52:38 -0700512 // slot_type values[max_count];
513 //
514 // // The array of child pointers. The keys in children[i] are all less
515 // // than key(i). The keys in children[i + 1] are all greater than key(i).
516 // // There are 0 children for leaf nodes and kNodeValues + 1 children for
517 // // internal nodes.
518 // btree_node *children[kNodeValues + 1];
519 //
520 // This class is only constructed by EmptyNodeType. Normally, pointers to the
521 // layout above are allocated, cast to btree_node*, and de-allocated within
522 // the btree implementation.
523 ~btree_node() = default;
524 btree_node(btree_node const &) = delete;
525 btree_node &operator=(btree_node const &) = delete;
526
527 // Public for EmptyNodeType.
528 constexpr static size_type Alignment() {
529 static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(),
530 "Alignment of all nodes must be equal.");
531 return InternalLayout().Alignment();
532 }
533
534 protected:
535 btree_node() = default;
536
537 private:
538 using layout_type = absl::container_internal::Layout<btree_node *, field_type,
539 slot_type, btree_node *>;
540 constexpr static size_type SizeWithNValues(size_type n) {
541 return layout_type(/*parent*/ 1,
Austin Schuhb4691e92020-12-31 12:37:18 -0800542 /*position, start, finish, max_count*/ 4,
Austin Schuh36244a12019-09-21 17:52:38 -0700543 /*values*/ n,
544 /*children*/ 0)
545 .AllocSize();
546 }
547 // A lower bound for the overhead of fields other than values in a leaf node.
548 constexpr static size_type MinimumOverhead() {
549 return SizeWithNValues(1) - sizeof(value_type);
550 }
551
552 // Compute how many values we can fit onto a leaf node taking into account
553 // padding.
554 constexpr static size_type NodeTargetValues(const int begin, const int end) {
555 return begin == end ? begin
556 : SizeWithNValues((begin + end) / 2 + 1) >
557 params_type::kTargetNodeSize
558 ? NodeTargetValues(begin, (begin + end) / 2)
559 : NodeTargetValues((begin + end) / 2 + 1, end);
560 }
561
562 enum {
563 kTargetNodeSize = params_type::kTargetNodeSize,
564 kNodeTargetValues = NodeTargetValues(0, params_type::kTargetNodeSize),
565
566 // We need a minimum of 3 values per internal node in order to perform
567 // splitting (1 value for the two nodes involved in the split and 1 value
568 // propagated to the parent as the delimiter for the split).
569 kNodeValues = kNodeTargetValues >= 3 ? kNodeTargetValues : 3,
570
571 // The node is internal (i.e. is not a leaf node) if and only if `max_count`
572 // has this value.
573 kInternalNodeMaxCount = 0,
574 };
575
576 // Leaves can have less than kNodeValues values.
577 constexpr static layout_type LeafLayout(const int max_values = kNodeValues) {
578 return layout_type(/*parent*/ 1,
Austin Schuhb4691e92020-12-31 12:37:18 -0800579 /*position, start, finish, max_count*/ 4,
Austin Schuh36244a12019-09-21 17:52:38 -0700580 /*values*/ max_values,
581 /*children*/ 0);
582 }
583 constexpr static layout_type InternalLayout() {
584 return layout_type(/*parent*/ 1,
Austin Schuhb4691e92020-12-31 12:37:18 -0800585 /*position, start, finish, max_count*/ 4,
Austin Schuh36244a12019-09-21 17:52:38 -0700586 /*values*/ kNodeValues,
587 /*children*/ kNodeValues + 1);
588 }
589 constexpr static size_type LeafSize(const int max_values = kNodeValues) {
590 return LeafLayout(max_values).AllocSize();
591 }
592 constexpr static size_type InternalSize() {
593 return InternalLayout().AllocSize();
594 }
595
596 // N is the index of the type in the Layout definition.
597 // ElementType<N> is the Nth type in the Layout definition.
598 template <size_type N>
599 inline typename layout_type::template ElementType<N> *GetField() {
600 // We assert that we don't read from values that aren't there.
601 assert(N < 3 || !leaf());
602 return InternalLayout().template Pointer<N>(reinterpret_cast<char *>(this));
603 }
604 template <size_type N>
605 inline const typename layout_type::template ElementType<N> *GetField() const {
606 assert(N < 3 || !leaf());
607 return InternalLayout().template Pointer<N>(
608 reinterpret_cast<const char *>(this));
609 }
610 void set_parent(btree_node *p) { *GetField<0>() = p; }
Austin Schuhb4691e92020-12-31 12:37:18 -0800611 field_type &mutable_finish() { return GetField<1>()[2]; }
Austin Schuh36244a12019-09-21 17:52:38 -0700612 slot_type *slot(int i) { return &GetField<2>()[i]; }
Austin Schuhb4691e92020-12-31 12:37:18 -0800613 slot_type *start_slot() { return slot(start()); }
614 slot_type *finish_slot() { return slot(finish()); }
Austin Schuh36244a12019-09-21 17:52:38 -0700615 const slot_type *slot(int i) const { return &GetField<2>()[i]; }
616 void set_position(field_type v) { GetField<1>()[0] = v; }
617 void set_start(field_type v) { GetField<1>()[1] = v; }
Austin Schuhb4691e92020-12-31 12:37:18 -0800618 void set_finish(field_type v) { GetField<1>()[2] = v; }
Austin Schuh36244a12019-09-21 17:52:38 -0700619 // This method is only called by the node init methods.
620 void set_max_count(field_type v) { GetField<1>()[3] = v; }
621
622 public:
623 // Whether this is a leaf node or not. This value doesn't change after the
624 // node is created.
625 bool leaf() const { return GetField<1>()[3] != kInternalNodeMaxCount; }
626
627 // Getter for the position of this node in its parent.
628 field_type position() const { return GetField<1>()[0]; }
629
630 // Getter for the offset of the first value in the `values` array.
Austin Schuhb4691e92020-12-31 12:37:18 -0800631 field_type start() const {
632 // TODO(ezb): when floating storage is implemented, return GetField<1>()[1];
633 assert(GetField<1>()[1] == 0);
634 return 0;
635 }
636
637 // Getter for the offset after the last value in the `values` array.
638 field_type finish() const { return GetField<1>()[2]; }
Austin Schuh36244a12019-09-21 17:52:38 -0700639
640 // Getters for the number of values stored in this node.
Austin Schuhb4691e92020-12-31 12:37:18 -0800641 field_type count() const {
642 assert(finish() >= start());
643 return finish() - start();
644 }
Austin Schuh36244a12019-09-21 17:52:38 -0700645 field_type max_count() const {
646 // Internal nodes have max_count==kInternalNodeMaxCount.
647 // Leaf nodes have max_count in [1, kNodeValues].
648 const field_type max_count = GetField<1>()[3];
649 return max_count == field_type{kInternalNodeMaxCount}
650 ? field_type{kNodeValues}
651 : max_count;
652 }
653
654 // Getter for the parent of this node.
655 btree_node *parent() const { return *GetField<0>(); }
656 // Getter for whether the node is the root of the tree. The parent of the
657 // root of the tree is the leftmost node in the tree which is guaranteed to
658 // be a leaf.
659 bool is_root() const { return parent()->leaf(); }
660 void make_root() {
661 assert(parent()->is_root());
662 set_parent(parent()->parent());
663 }
664
665 // Getters for the key/value at position i in the node.
666 const key_type &key(int i) const { return params_type::key(slot(i)); }
667 reference value(int i) { return params_type::element(slot(i)); }
668 const_reference value(int i) const { return params_type::element(slot(i)); }
669
670 // Getters/setter for the child at position i in the node.
671 btree_node *child(int i) const { return GetField<3>()[i]; }
Austin Schuhb4691e92020-12-31 12:37:18 -0800672 btree_node *start_child() const { return child(start()); }
Austin Schuh36244a12019-09-21 17:52:38 -0700673 btree_node *&mutable_child(int i) { return GetField<3>()[i]; }
674 void clear_child(int i) {
675 absl::container_internal::SanitizerPoisonObject(&mutable_child(i));
676 }
677 void set_child(int i, btree_node *c) {
678 absl::container_internal::SanitizerUnpoisonObject(&mutable_child(i));
679 mutable_child(i) = c;
680 c->set_position(i);
681 }
682 void init_child(int i, btree_node *c) {
683 set_child(i, c);
684 c->set_parent(this);
685 }
686
687 // Returns the position of the first value whose key is not less than k.
688 template <typename K>
689 SearchResult<int, is_key_compare_to::value> lower_bound(
690 const K &k, const key_compare &comp) const {
691 return use_linear_search::value ? linear_search(k, comp)
692 : binary_search(k, comp);
693 }
694 // Returns the position of the first value whose key is greater than k.
695 template <typename K>
696 int upper_bound(const K &k, const key_compare &comp) const {
697 auto upper_compare = upper_bound_adapter<key_compare>(comp);
698 return use_linear_search::value ? linear_search(k, upper_compare).value
699 : binary_search(k, upper_compare).value;
700 }
701
702 template <typename K, typename Compare>
703 SearchResult<int, btree_is_key_compare_to<Compare, key_type>::value>
704 linear_search(const K &k, const Compare &comp) const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800705 return linear_search_impl(k, start(), finish(), comp,
Austin Schuh36244a12019-09-21 17:52:38 -0700706 btree_is_key_compare_to<Compare, key_type>());
707 }
708
709 template <typename K, typename Compare>
710 SearchResult<int, btree_is_key_compare_to<Compare, key_type>::value>
711 binary_search(const K &k, const Compare &comp) const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800712 return binary_search_impl(k, start(), finish(), comp,
Austin Schuh36244a12019-09-21 17:52:38 -0700713 btree_is_key_compare_to<Compare, key_type>());
714 }
715
716 // Returns the position of the first value whose key is not less than k using
717 // linear search performed using plain compare.
718 template <typename K, typename Compare>
719 SearchResult<int, false> linear_search_impl(
720 const K &k, int s, const int e, const Compare &comp,
721 std::false_type /* IsCompareTo */) const {
722 while (s < e) {
723 if (!comp(key(s), k)) {
724 break;
725 }
726 ++s;
727 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800728 return SearchResult<int, false>{s};
Austin Schuh36244a12019-09-21 17:52:38 -0700729 }
730
731 // Returns the position of the first value whose key is not less than k using
732 // linear search performed using compare-to.
733 template <typename K, typename Compare>
734 SearchResult<int, true> linear_search_impl(
735 const K &k, int s, const int e, const Compare &comp,
736 std::true_type /* IsCompareTo */) const {
737 while (s < e) {
738 const absl::weak_ordering c = comp(key(s), k);
739 if (c == 0) {
740 return {s, MatchKind::kEq};
741 } else if (c > 0) {
742 break;
743 }
744 ++s;
745 }
746 return {s, MatchKind::kNe};
747 }
748
749 // Returns the position of the first value whose key is not less than k using
750 // binary search performed using plain compare.
751 template <typename K, typename Compare>
752 SearchResult<int, false> binary_search_impl(
753 const K &k, int s, int e, const Compare &comp,
754 std::false_type /* IsCompareTo */) const {
755 while (s != e) {
756 const int mid = (s + e) >> 1;
757 if (comp(key(mid), k)) {
758 s = mid + 1;
759 } else {
760 e = mid;
761 }
762 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800763 return SearchResult<int, false>{s};
Austin Schuh36244a12019-09-21 17:52:38 -0700764 }
765
766 // Returns the position of the first value whose key is not less than k using
767 // binary search performed using compare-to.
768 template <typename K, typename CompareTo>
769 SearchResult<int, true> binary_search_impl(
770 const K &k, int s, int e, const CompareTo &comp,
771 std::true_type /* IsCompareTo */) const {
Austin Schuhb4691e92020-12-31 12:37:18 -0800772 if (params_type::template can_have_multiple_equivalent_keys<K>()) {
Austin Schuh36244a12019-09-21 17:52:38 -0700773 MatchKind exact_match = MatchKind::kNe;
774 while (s != e) {
775 const int mid = (s + e) >> 1;
776 const absl::weak_ordering c = comp(key(mid), k);
777 if (c < 0) {
778 s = mid + 1;
779 } else {
780 e = mid;
781 if (c == 0) {
782 // Need to return the first value whose key is not less than k,
Austin Schuhb4691e92020-12-31 12:37:18 -0800783 // which requires continuing the binary search if there could be
784 // multiple equivalent keys.
Austin Schuh36244a12019-09-21 17:52:38 -0700785 exact_match = MatchKind::kEq;
786 }
787 }
788 }
789 return {s, exact_match};
Austin Schuhb4691e92020-12-31 12:37:18 -0800790 } else { // Can't have multiple equivalent keys.
Austin Schuh36244a12019-09-21 17:52:38 -0700791 while (s != e) {
792 const int mid = (s + e) >> 1;
793 const absl::weak_ordering c = comp(key(mid), k);
794 if (c < 0) {
795 s = mid + 1;
796 } else if (c > 0) {
797 e = mid;
798 } else {
799 return {mid, MatchKind::kEq};
800 }
801 }
802 return {s, MatchKind::kNe};
803 }
804 }
805
806 // Emplaces a value at position i, shifting all existing values and
807 // children at positions >= i to the right by 1.
808 template <typename... Args>
809 void emplace_value(size_type i, allocator_type *alloc, Args &&... args);
810
Austin Schuhb4691e92020-12-31 12:37:18 -0800811 // Removes the values at positions [i, i + to_erase), shifting all existing
812 // values and children after that range to the left by to_erase. Clears all
813 // children between [i, i + to_erase).
814 void remove_values(field_type i, field_type to_erase, allocator_type *alloc);
Austin Schuh36244a12019-09-21 17:52:38 -0700815
816 // Rebalances a node with its right sibling.
817 void rebalance_right_to_left(int to_move, btree_node *right,
818 allocator_type *alloc);
819 void rebalance_left_to_right(int to_move, btree_node *right,
820 allocator_type *alloc);
821
822 // Splits a node, moving a portion of the node's values to its right sibling.
823 void split(int insert_position, btree_node *dest, allocator_type *alloc);
824
825 // Merges a node with its right sibling, moving all of the values and the
Austin Schuhb4691e92020-12-31 12:37:18 -0800826 // delimiting key in the parent node onto itself, and deleting the src node.
827 void merge(btree_node *src, allocator_type *alloc);
Austin Schuh36244a12019-09-21 17:52:38 -0700828
829 // Node allocation/deletion routines.
Austin Schuhb4691e92020-12-31 12:37:18 -0800830 void init_leaf(btree_node *parent, int max_count) {
831 set_parent(parent);
832 set_position(0);
833 set_start(0);
834 set_finish(0);
835 set_max_count(max_count);
Austin Schuh36244a12019-09-21 17:52:38 -0700836 absl::container_internal::SanitizerPoisonMemoryRegion(
Austin Schuhb4691e92020-12-31 12:37:18 -0800837 start_slot(), max_count * sizeof(slot_type));
Austin Schuh36244a12019-09-21 17:52:38 -0700838 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800839 void init_internal(btree_node *parent) {
840 init_leaf(parent, kNodeValues);
Austin Schuh36244a12019-09-21 17:52:38 -0700841 // Set `max_count` to a sentinel value to indicate that this node is
842 // internal.
Austin Schuhb4691e92020-12-31 12:37:18 -0800843 set_max_count(kInternalNodeMaxCount);
Austin Schuh36244a12019-09-21 17:52:38 -0700844 absl::container_internal::SanitizerPoisonMemoryRegion(
Austin Schuhb4691e92020-12-31 12:37:18 -0800845 &mutable_child(start()), (kNodeValues + 1) * sizeof(btree_node *));
Austin Schuh36244a12019-09-21 17:52:38 -0700846 }
847
Austin Schuhb4691e92020-12-31 12:37:18 -0800848 static void deallocate(const size_type size, btree_node *node,
849 allocator_type *alloc) {
850 absl::container_internal::Deallocate<Alignment()>(alloc, node, size);
Austin Schuh36244a12019-09-21 17:52:38 -0700851 }
852
Austin Schuhb4691e92020-12-31 12:37:18 -0800853 // Deletes a node and all of its children.
854 static void clear_and_delete(btree_node *node, allocator_type *alloc);
855
Austin Schuh36244a12019-09-21 17:52:38 -0700856 private:
857 template <typename... Args>
Austin Schuhb4691e92020-12-31 12:37:18 -0800858 void value_init(const field_type i, allocator_type *alloc, Args &&... args) {
Austin Schuh36244a12019-09-21 17:52:38 -0700859 absl::container_internal::SanitizerUnpoisonObject(slot(i));
860 params_type::construct(alloc, slot(i), std::forward<Args>(args)...);
861 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800862 void value_destroy(const field_type i, allocator_type *alloc) {
Austin Schuh36244a12019-09-21 17:52:38 -0700863 params_type::destroy(alloc, slot(i));
864 absl::container_internal::SanitizerPoisonObject(slot(i));
865 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800866 void value_destroy_n(const field_type i, const field_type n,
867 allocator_type *alloc) {
868 for (slot_type *s = slot(i), *end = slot(i + n); s != end; ++s) {
869 params_type::destroy(alloc, s);
870 absl::container_internal::SanitizerPoisonObject(s);
Austin Schuh36244a12019-09-21 17:52:38 -0700871 }
872 }
873
Austin Schuhb4691e92020-12-31 12:37:18 -0800874 static void transfer(slot_type *dest, slot_type *src, allocator_type *alloc) {
875 absl::container_internal::SanitizerUnpoisonObject(dest);
876 params_type::transfer(alloc, dest, src);
877 absl::container_internal::SanitizerPoisonObject(src);
878 }
879
880 // Transfers value from slot `src_i` in `src_node` to slot `dest_i` in `this`.
881 void transfer(const size_type dest_i, const size_type src_i,
882 btree_node *src_node, allocator_type *alloc) {
883 transfer(slot(dest_i), src_node->slot(src_i), alloc);
884 }
885
886 // Transfers `n` values starting at value `src_i` in `src_node` into the
887 // values starting at value `dest_i` in `this`.
888 void transfer_n(const size_type n, const size_type dest_i,
889 const size_type src_i, btree_node *src_node,
890 allocator_type *alloc) {
891 for (slot_type *src = src_node->slot(src_i), *end = src + n,
892 *dest = slot(dest_i);
893 src != end; ++src, ++dest) {
894 transfer(dest, src, alloc);
895 }
896 }
897
898 // Same as above, except that we start at the end and work our way to the
899 // beginning.
900 void transfer_n_backward(const size_type n, const size_type dest_i,
901 const size_type src_i, btree_node *src_node,
902 allocator_type *alloc) {
903 for (slot_type *src = src_node->slot(src_i + n - 1), *end = src - n,
904 *dest = slot(dest_i + n - 1);
905 src != end; --src, --dest) {
906 transfer(dest, src, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -0700907 }
908 }
909
910 template <typename P>
911 friend class btree;
912 template <typename N, typename R, typename P>
913 friend struct btree_iterator;
914 friend class BtreeNodePeer;
915};
916
917template <typename Node, typename Reference, typename Pointer>
918struct btree_iterator {
919 private:
920 using key_type = typename Node::key_type;
921 using size_type = typename Node::size_type;
922 using params_type = typename Node::params_type;
Austin Schuhb4691e92020-12-31 12:37:18 -0800923 using is_map_container = typename params_type::is_map_container;
Austin Schuh36244a12019-09-21 17:52:38 -0700924
925 using node_type = Node;
926 using normal_node = typename std::remove_const<Node>::type;
927 using const_node = const Node;
928 using normal_pointer = typename params_type::pointer;
929 using normal_reference = typename params_type::reference;
930 using const_pointer = typename params_type::const_pointer;
931 using const_reference = typename params_type::const_reference;
932 using slot_type = typename params_type::slot_type;
933
934 using iterator =
Austin Schuhb4691e92020-12-31 12:37:18 -0800935 btree_iterator<normal_node, normal_reference, normal_pointer>;
Austin Schuh36244a12019-09-21 17:52:38 -0700936 using const_iterator =
937 btree_iterator<const_node, const_reference, const_pointer>;
938
939 public:
940 // These aliases are public for std::iterator_traits.
941 using difference_type = typename Node::difference_type;
942 using value_type = typename params_type::value_type;
943 using pointer = Pointer;
944 using reference = Reference;
945 using iterator_category = std::bidirectional_iterator_tag;
946
947 btree_iterator() : node(nullptr), position(-1) {}
Austin Schuhb4691e92020-12-31 12:37:18 -0800948 explicit btree_iterator(Node *n) : node(n), position(n->start()) {}
Austin Schuh36244a12019-09-21 17:52:38 -0700949 btree_iterator(Node *n, int p) : node(n), position(p) {}
950
951 // NOTE: this SFINAE allows for implicit conversions from iterator to
Austin Schuhb4691e92020-12-31 12:37:18 -0800952 // const_iterator, but it specifically avoids hiding the copy constructor so
953 // that the trivial one will be used when possible.
Austin Schuh36244a12019-09-21 17:52:38 -0700954 template <typename N, typename R, typename P,
955 absl::enable_if_t<
956 std::is_same<btree_iterator<N, R, P>, iterator>::value &&
957 std::is_same<btree_iterator, const_iterator>::value,
958 int> = 0>
Austin Schuhb4691e92020-12-31 12:37:18 -0800959 btree_iterator(const btree_iterator<N, R, P> other) // NOLINT
960 : node(other.node), position(other.position) {}
Austin Schuh36244a12019-09-21 17:52:38 -0700961
962 private:
963 // This SFINAE allows explicit conversions from const_iterator to
Austin Schuhb4691e92020-12-31 12:37:18 -0800964 // iterator, but also avoids hiding the copy constructor.
Austin Schuh36244a12019-09-21 17:52:38 -0700965 // NOTE: the const_cast is safe because this constructor is only called by
966 // non-const methods and the container owns the nodes.
967 template <typename N, typename R, typename P,
968 absl::enable_if_t<
969 std::is_same<btree_iterator<N, R, P>, const_iterator>::value &&
970 std::is_same<btree_iterator, iterator>::value,
971 int> = 0>
Austin Schuhb4691e92020-12-31 12:37:18 -0800972 explicit btree_iterator(const btree_iterator<N, R, P> other)
973 : node(const_cast<node_type *>(other.node)), position(other.position) {}
Austin Schuh36244a12019-09-21 17:52:38 -0700974
975 // Increment/decrement the iterator.
976 void increment() {
Austin Schuhb4691e92020-12-31 12:37:18 -0800977 if (node->leaf() && ++position < node->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -0700978 return;
979 }
980 increment_slow();
981 }
982 void increment_slow();
983
984 void decrement() {
Austin Schuhb4691e92020-12-31 12:37:18 -0800985 if (node->leaf() && --position >= node->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -0700986 return;
987 }
988 decrement_slow();
989 }
990 void decrement_slow();
991
992 public:
Austin Schuhb4691e92020-12-31 12:37:18 -0800993 bool operator==(const iterator &other) const {
994 return node == other.node && position == other.position;
Austin Schuh36244a12019-09-21 17:52:38 -0700995 }
Austin Schuhb4691e92020-12-31 12:37:18 -0800996 bool operator==(const const_iterator &other) const {
997 return node == other.node && position == other.position;
998 }
999 bool operator!=(const iterator &other) const {
1000 return node != other.node || position != other.position;
1001 }
1002 bool operator!=(const const_iterator &other) const {
1003 return node != other.node || position != other.position;
Austin Schuh36244a12019-09-21 17:52:38 -07001004 }
1005
1006 // Accessors for the key/value the iterator is pointing at.
1007 reference operator*() const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001008 ABSL_HARDENING_ASSERT(node != nullptr);
1009 ABSL_HARDENING_ASSERT(node->start() <= position);
1010 ABSL_HARDENING_ASSERT(node->finish() > position);
Austin Schuh36244a12019-09-21 17:52:38 -07001011 return node->value(position);
1012 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001013 pointer operator->() const { return &operator*(); }
Austin Schuh36244a12019-09-21 17:52:38 -07001014
Austin Schuhb4691e92020-12-31 12:37:18 -08001015 btree_iterator &operator++() {
Austin Schuh36244a12019-09-21 17:52:38 -07001016 increment();
1017 return *this;
1018 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001019 btree_iterator &operator--() {
Austin Schuh36244a12019-09-21 17:52:38 -07001020 decrement();
1021 return *this;
1022 }
1023 btree_iterator operator++(int) {
1024 btree_iterator tmp = *this;
1025 ++*this;
1026 return tmp;
1027 }
1028 btree_iterator operator--(int) {
1029 btree_iterator tmp = *this;
1030 --*this;
1031 return tmp;
1032 }
1033
1034 private:
Austin Schuhb4691e92020-12-31 12:37:18 -08001035 friend iterator;
1036 friend const_iterator;
Austin Schuh36244a12019-09-21 17:52:38 -07001037 template <typename Params>
1038 friend class btree;
1039 template <typename Tree>
1040 friend class btree_container;
1041 template <typename Tree>
1042 friend class btree_set_container;
1043 template <typename Tree>
1044 friend class btree_map_container;
1045 template <typename Tree>
1046 friend class btree_multiset_container;
Austin Schuh36244a12019-09-21 17:52:38 -07001047 template <typename TreeType, typename CheckerType>
1048 friend class base_checker;
1049
1050 const key_type &key() const { return node->key(position); }
1051 slot_type *slot() { return node->slot(position); }
1052
1053 // The node in the tree the iterator is pointing at.
1054 Node *node;
1055 // The position within the node of the tree the iterator is pointing at.
Austin Schuhb4691e92020-12-31 12:37:18 -08001056 // NOTE: this is an int rather than a field_type because iterators can point
1057 // to invalid positions (such as -1) in certain circumstances.
Austin Schuh36244a12019-09-21 17:52:38 -07001058 int position;
1059};
1060
1061template <typename Params>
1062class btree {
1063 using node_type = btree_node<Params>;
1064 using is_key_compare_to = typename Params::is_key_compare_to;
Austin Schuhb4691e92020-12-31 12:37:18 -08001065 using init_type = typename Params::init_type;
1066 using field_type = typename node_type::field_type;
Austin Schuh36244a12019-09-21 17:52:38 -07001067
1068 // We use a static empty node for the root/leftmost/rightmost of empty btrees
1069 // in order to avoid branching in begin()/end().
1070 struct alignas(node_type::Alignment()) EmptyNodeType : node_type {
1071 using field_type = typename node_type::field_type;
1072 node_type *parent;
1073 field_type position = 0;
1074 field_type start = 0;
Austin Schuhb4691e92020-12-31 12:37:18 -08001075 field_type finish = 0;
Austin Schuh36244a12019-09-21 17:52:38 -07001076 // max_count must be != kInternalNodeMaxCount (so that this node is regarded
1077 // as a leaf node). max_count() is never called when the tree is empty.
1078 field_type max_count = node_type::kInternalNodeMaxCount + 1;
1079
1080#ifdef _MSC_VER
1081 // MSVC has constexpr code generations bugs here.
1082 EmptyNodeType() : parent(this) {}
1083#else
1084 constexpr EmptyNodeType(node_type *p) : parent(p) {}
1085#endif
1086 };
1087
1088 static node_type *EmptyNode() {
1089#ifdef _MSC_VER
Austin Schuhb4691e92020-12-31 12:37:18 -08001090 static EmptyNodeType *empty_node = new EmptyNodeType;
Austin Schuh36244a12019-09-21 17:52:38 -07001091 // This assert fails on some other construction methods.
1092 assert(empty_node->parent == empty_node);
1093 return empty_node;
1094#else
1095 static constexpr EmptyNodeType empty_node(
1096 const_cast<EmptyNodeType *>(&empty_node));
1097 return const_cast<EmptyNodeType *>(&empty_node);
1098#endif
1099 }
1100
Austin Schuhb4691e92020-12-31 12:37:18 -08001101 enum : uint32_t {
Austin Schuh36244a12019-09-21 17:52:38 -07001102 kNodeValues = node_type::kNodeValues,
1103 kMinNodeValues = kNodeValues / 2,
1104 };
1105
1106 struct node_stats {
1107 using size_type = typename Params::size_type;
1108
Austin Schuhb4691e92020-12-31 12:37:18 -08001109 node_stats(size_type l, size_type i) : leaf_nodes(l), internal_nodes(i) {}
Austin Schuh36244a12019-09-21 17:52:38 -07001110
Austin Schuhb4691e92020-12-31 12:37:18 -08001111 node_stats &operator+=(const node_stats &other) {
1112 leaf_nodes += other.leaf_nodes;
1113 internal_nodes += other.internal_nodes;
Austin Schuh36244a12019-09-21 17:52:38 -07001114 return *this;
1115 }
1116
1117 size_type leaf_nodes;
1118 size_type internal_nodes;
1119 };
1120
1121 public:
1122 using key_type = typename Params::key_type;
1123 using value_type = typename Params::value_type;
1124 using size_type = typename Params::size_type;
1125 using difference_type = typename Params::difference_type;
1126 using key_compare = typename Params::key_compare;
1127 using value_compare = typename Params::value_compare;
1128 using allocator_type = typename Params::allocator_type;
1129 using reference = typename Params::reference;
1130 using const_reference = typename Params::const_reference;
1131 using pointer = typename Params::pointer;
1132 using const_pointer = typename Params::const_pointer;
Austin Schuhb4691e92020-12-31 12:37:18 -08001133 using iterator =
1134 typename btree_iterator<node_type, reference, pointer>::iterator;
Austin Schuh36244a12019-09-21 17:52:38 -07001135 using const_iterator = typename iterator::const_iterator;
1136 using reverse_iterator = std::reverse_iterator<iterator>;
1137 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
1138 using node_handle_type = node_handle<Params, Params, allocator_type>;
1139
1140 // Internal types made public for use by btree_container types.
1141 using params_type = Params;
1142 using slot_type = typename Params::slot_type;
1143
1144 private:
1145 // For use in copy_or_move_values_in_order.
Austin Schuhb4691e92020-12-31 12:37:18 -08001146 const value_type &maybe_move_from_iterator(const_iterator it) { return *it; }
1147 value_type &&maybe_move_from_iterator(iterator it) {
1148 // This is a destructive operation on the other container so it's safe for
1149 // us to const_cast and move from the keys here even if it's a set.
1150 return std::move(const_cast<value_type &>(*it));
1151 }
Austin Schuh36244a12019-09-21 17:52:38 -07001152
1153 // Copies or moves (depending on the template parameter) the values in
Austin Schuhb4691e92020-12-31 12:37:18 -08001154 // other into this btree in their order in other. This btree must be empty
1155 // before this method is called. This method is used in copy construction,
1156 // copy assignment, and move assignment.
Austin Schuh36244a12019-09-21 17:52:38 -07001157 template <typename Btree>
Austin Schuhb4691e92020-12-31 12:37:18 -08001158 void copy_or_move_values_in_order(Btree &other);
Austin Schuh36244a12019-09-21 17:52:38 -07001159
1160 // Validates that various assumptions/requirements are true at compile time.
1161 constexpr static bool static_assert_validation();
1162
1163 public:
Austin Schuhb4691e92020-12-31 12:37:18 -08001164 btree(const key_compare &comp, const allocator_type &alloc)
1165 : root_(comp, alloc, EmptyNode()), rightmost_(EmptyNode()), size_(0) {}
Austin Schuh36244a12019-09-21 17:52:38 -07001166
Austin Schuhb4691e92020-12-31 12:37:18 -08001167 btree(const btree &other) : btree(other, other.allocator()) {}
1168 btree(const btree &other, const allocator_type &alloc)
1169 : btree(other.key_comp(), alloc) {
1170 copy_or_move_values_in_order(other);
1171 }
1172 btree(btree &&other) noexcept
1173 : root_(std::move(other.root_)),
1174 rightmost_(absl::exchange(other.rightmost_, EmptyNode())),
1175 size_(absl::exchange(other.size_, 0)) {
1176 other.mutable_root() = EmptyNode();
1177 }
1178 btree(btree &&other, const allocator_type &alloc)
1179 : btree(other.key_comp(), alloc) {
1180 if (alloc == other.allocator()) {
1181 swap(other);
1182 } else {
1183 // Move values from `other` one at a time when allocators are different.
1184 copy_or_move_values_in_order(other);
1185 }
Austin Schuh36244a12019-09-21 17:52:38 -07001186 }
1187
1188 ~btree() {
1189 // Put static_asserts in destructor to avoid triggering them before the type
1190 // is complete.
1191 static_assert(static_assert_validation(), "This call must be elided.");
1192 clear();
1193 }
1194
Austin Schuhb4691e92020-12-31 12:37:18 -08001195 // Assign the contents of other to *this.
1196 btree &operator=(const btree &other);
1197 btree &operator=(btree &&other) noexcept;
Austin Schuh36244a12019-09-21 17:52:38 -07001198
Austin Schuhb4691e92020-12-31 12:37:18 -08001199 iterator begin() { return iterator(leftmost()); }
1200 const_iterator begin() const { return const_iterator(leftmost()); }
1201 iterator end() { return iterator(rightmost_, rightmost_->finish()); }
Austin Schuh36244a12019-09-21 17:52:38 -07001202 const_iterator end() const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001203 return const_iterator(rightmost_, rightmost_->finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001204 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001205 reverse_iterator rbegin() { return reverse_iterator(end()); }
Austin Schuh36244a12019-09-21 17:52:38 -07001206 const_reverse_iterator rbegin() const {
1207 return const_reverse_iterator(end());
1208 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001209 reverse_iterator rend() { return reverse_iterator(begin()); }
Austin Schuh36244a12019-09-21 17:52:38 -07001210 const_reverse_iterator rend() const {
1211 return const_reverse_iterator(begin());
1212 }
1213
Austin Schuhb4691e92020-12-31 12:37:18 -08001214 // Finds the first element whose key is not less than `key`.
Austin Schuh36244a12019-09-21 17:52:38 -07001215 template <typename K>
1216 iterator lower_bound(const K &key) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001217 return internal_end(internal_lower_bound(key).value);
Austin Schuh36244a12019-09-21 17:52:38 -07001218 }
1219 template <typename K>
1220 const_iterator lower_bound(const K &key) const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001221 return internal_end(internal_lower_bound(key).value);
Austin Schuh36244a12019-09-21 17:52:38 -07001222 }
1223
Austin Schuhb4691e92020-12-31 12:37:18 -08001224 // Finds the first element whose key is not less than `key` and also returns
1225 // whether that element is equal to `key`.
1226 template <typename K>
1227 std::pair<iterator, bool> lower_bound_equal(const K &key) const;
1228
1229 // Finds the first element whose key is greater than `key`.
Austin Schuh36244a12019-09-21 17:52:38 -07001230 template <typename K>
1231 iterator upper_bound(const K &key) {
1232 return internal_end(internal_upper_bound(key));
1233 }
1234 template <typename K>
1235 const_iterator upper_bound(const K &key) const {
1236 return internal_end(internal_upper_bound(key));
1237 }
1238
1239 // Finds the range of values which compare equal to key. The first member of
Austin Schuhb4691e92020-12-31 12:37:18 -08001240 // the returned pair is equal to lower_bound(key). The second member of the
1241 // pair is equal to upper_bound(key).
Austin Schuh36244a12019-09-21 17:52:38 -07001242 template <typename K>
Austin Schuhb4691e92020-12-31 12:37:18 -08001243 std::pair<iterator, iterator> equal_range(const K &key);
Austin Schuh36244a12019-09-21 17:52:38 -07001244 template <typename K>
1245 std::pair<const_iterator, const_iterator> equal_range(const K &key) const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001246 return const_cast<btree *>(this)->equal_range(key);
Austin Schuh36244a12019-09-21 17:52:38 -07001247 }
1248
1249 // Inserts a value into the btree only if it does not already exist. The
1250 // boolean return value indicates whether insertion succeeded or failed.
1251 // Requirement: if `key` already exists in the btree, does not consume `args`.
1252 // Requirement: `key` is never referenced after consuming `args`.
Austin Schuhb4691e92020-12-31 12:37:18 -08001253 template <typename K, typename... Args>
1254 std::pair<iterator, bool> insert_unique(const K &key, Args &&... args);
Austin Schuh36244a12019-09-21 17:52:38 -07001255
1256 // Inserts with hint. Checks to see if the value should be placed immediately
1257 // before `position` in the tree. If so, then the insertion will take
1258 // amortized constant time. If not, the insertion will take amortized
1259 // logarithmic time as if a call to insert_unique() were made.
1260 // Requirement: if `key` already exists in the btree, does not consume `args`.
1261 // Requirement: `key` is never referenced after consuming `args`.
Austin Schuhb4691e92020-12-31 12:37:18 -08001262 template <typename K, typename... Args>
Austin Schuh36244a12019-09-21 17:52:38 -07001263 std::pair<iterator, bool> insert_hint_unique(iterator position,
Austin Schuhb4691e92020-12-31 12:37:18 -08001264 const K &key,
Austin Schuh36244a12019-09-21 17:52:38 -07001265 Args &&... args);
1266
1267 // Insert a range of values into the btree.
Austin Schuhb4691e92020-12-31 12:37:18 -08001268 // Note: the first overload avoids constructing a value_type if the key
1269 // already exists in the btree.
1270 template <typename InputIterator,
1271 typename = decltype(std::declval<const key_compare &>()(
1272 params_type::key(*std::declval<InputIterator>()),
1273 std::declval<const key_type &>()))>
1274 void insert_iterator_unique(InputIterator b, InputIterator e, int);
1275 // We need the second overload for cases in which we need to construct a
1276 // value_type in order to compare it with the keys already in the btree.
Austin Schuh36244a12019-09-21 17:52:38 -07001277 template <typename InputIterator>
Austin Schuhb4691e92020-12-31 12:37:18 -08001278 void insert_iterator_unique(InputIterator b, InputIterator e, char);
Austin Schuh36244a12019-09-21 17:52:38 -07001279
1280 // Inserts a value into the btree.
1281 template <typename ValueType>
1282 iterator insert_multi(const key_type &key, ValueType &&v);
1283
1284 // Inserts a value into the btree.
1285 template <typename ValueType>
1286 iterator insert_multi(ValueType &&v) {
1287 return insert_multi(params_type::key(v), std::forward<ValueType>(v));
1288 }
1289
1290 // Insert with hint. Check to see if the value should be placed immediately
1291 // before position in the tree. If it does, then the insertion will take
1292 // amortized constant time. If not, the insertion will take amortized
1293 // logarithmic time as if a call to insert_multi(v) were made.
1294 template <typename ValueType>
1295 iterator insert_hint_multi(iterator position, ValueType &&v);
1296
1297 // Insert a range of values into the btree.
1298 template <typename InputIterator>
1299 void insert_iterator_multi(InputIterator b, InputIterator e);
1300
1301 // Erase the specified iterator from the btree. The iterator must be valid
1302 // (i.e. not equal to end()). Return an iterator pointing to the node after
1303 // the one that was erased (or end() if none exists).
1304 // Requirement: does not read the value at `*iter`.
1305 iterator erase(iterator iter);
1306
1307 // Erases range. Returns the number of keys erased and an iterator pointing
1308 // to the element after the last erased element.
Austin Schuhb4691e92020-12-31 12:37:18 -08001309 std::pair<size_type, iterator> erase_range(iterator begin, iterator end);
Austin Schuh36244a12019-09-21 17:52:38 -07001310
Austin Schuhb4691e92020-12-31 12:37:18 -08001311 // Finds an element with key equivalent to `key` or returns `end()` if `key`
1312 // is not present.
Austin Schuh36244a12019-09-21 17:52:38 -07001313 template <typename K>
1314 iterator find(const K &key) {
1315 return internal_end(internal_find(key));
1316 }
1317 template <typename K>
1318 const_iterator find(const K &key) const {
1319 return internal_end(internal_find(key));
1320 }
1321
Austin Schuh36244a12019-09-21 17:52:38 -07001322 // Clear the btree, deleting all of the values it contains.
1323 void clear();
1324
Austin Schuhb4691e92020-12-31 12:37:18 -08001325 // Swaps the contents of `this` and `other`.
1326 void swap(btree &other);
Austin Schuh36244a12019-09-21 17:52:38 -07001327
1328 const key_compare &key_comp() const noexcept {
1329 return root_.template get<0>();
1330 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001331 template <typename K1, typename K2>
1332 bool compare_keys(const K1 &a, const K2 &b) const {
1333 return compare_internal::compare_result_as_less_than(key_comp()(a, b));
Austin Schuh36244a12019-09-21 17:52:38 -07001334 }
1335
1336 value_compare value_comp() const { return value_compare(key_comp()); }
1337
1338 // Verifies the structure of the btree.
1339 void verify() const;
1340
1341 // Size routines.
1342 size_type size() const { return size_; }
1343 size_type max_size() const { return (std::numeric_limits<size_type>::max)(); }
1344 bool empty() const { return size_ == 0; }
1345
1346 // The height of the btree. An empty tree will have height 0.
1347 size_type height() const {
1348 size_type h = 0;
Austin Schuhb4691e92020-12-31 12:37:18 -08001349 if (!empty()) {
Austin Schuh36244a12019-09-21 17:52:38 -07001350 // Count the length of the chain from the leftmost node up to the
1351 // root. We actually count from the root back around to the level below
1352 // the root, but the calculation is the same because of the circularity
1353 // of that traversal.
1354 const node_type *n = root();
1355 do {
1356 ++h;
1357 n = n->parent();
1358 } while (n != root());
1359 }
1360 return h;
1361 }
1362
1363 // The number of internal, leaf and total nodes used by the btree.
Austin Schuhb4691e92020-12-31 12:37:18 -08001364 size_type leaf_nodes() const { return internal_stats(root()).leaf_nodes; }
Austin Schuh36244a12019-09-21 17:52:38 -07001365 size_type internal_nodes() const {
1366 return internal_stats(root()).internal_nodes;
1367 }
1368 size_type nodes() const {
1369 node_stats stats = internal_stats(root());
1370 return stats.leaf_nodes + stats.internal_nodes;
1371 }
1372
1373 // The total number of bytes used by the btree.
1374 size_type bytes_used() const {
1375 node_stats stats = internal_stats(root());
1376 if (stats.leaf_nodes == 1 && stats.internal_nodes == 0) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001377 return sizeof(*this) + node_type::LeafSize(root()->max_count());
Austin Schuh36244a12019-09-21 17:52:38 -07001378 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08001379 return sizeof(*this) + stats.leaf_nodes * node_type::LeafSize() +
Austin Schuh36244a12019-09-21 17:52:38 -07001380 stats.internal_nodes * node_type::InternalSize();
1381 }
1382 }
1383
1384 // The average number of bytes used per value stored in the btree.
1385 static double average_bytes_per_value() {
1386 // Returns the number of bytes per value on a leaf node that is 75%
1387 // full. Experimentally, this matches up nicely with the computed number of
1388 // bytes per value in trees that had their values inserted in random order.
1389 return node_type::LeafSize() / (kNodeValues * 0.75);
1390 }
1391
1392 // The fullness of the btree. Computed as the number of elements in the btree
1393 // divided by the maximum number of elements a tree with the current number
1394 // of nodes could hold. A value of 1 indicates perfect space
1395 // utilization. Smaller values indicate space wastage.
Austin Schuhb4691e92020-12-31 12:37:18 -08001396 // Returns 0 for empty trees.
Austin Schuh36244a12019-09-21 17:52:38 -07001397 double fullness() const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001398 if (empty()) return 0.0;
Austin Schuh36244a12019-09-21 17:52:38 -07001399 return static_cast<double>(size()) / (nodes() * kNodeValues);
1400 }
1401 // The overhead of the btree structure in bytes per node. Computed as the
1402 // total number of bytes used by the btree minus the number of bytes used for
1403 // storing elements divided by the number of elements.
Austin Schuhb4691e92020-12-31 12:37:18 -08001404 // Returns 0 for empty trees.
Austin Schuh36244a12019-09-21 17:52:38 -07001405 double overhead() const {
Austin Schuhb4691e92020-12-31 12:37:18 -08001406 if (empty()) return 0.0;
Austin Schuh36244a12019-09-21 17:52:38 -07001407 return (bytes_used() - size() * sizeof(value_type)) /
1408 static_cast<double>(size());
1409 }
1410
1411 // The allocator used by the btree.
Austin Schuhb4691e92020-12-31 12:37:18 -08001412 allocator_type get_allocator() const { return allocator(); }
Austin Schuh36244a12019-09-21 17:52:38 -07001413
1414 private:
1415 // Internal accessor routines.
1416 node_type *root() { return root_.template get<2>(); }
1417 const node_type *root() const { return root_.template get<2>(); }
1418 node_type *&mutable_root() noexcept { return root_.template get<2>(); }
1419 key_compare *mutable_key_comp() noexcept { return &root_.template get<0>(); }
1420
1421 // The leftmost node is stored as the parent of the root node.
1422 node_type *leftmost() { return root()->parent(); }
1423 const node_type *leftmost() const { return root()->parent(); }
1424
1425 // Allocator routines.
1426 allocator_type *mutable_allocator() noexcept {
1427 return &root_.template get<1>();
1428 }
1429 const allocator_type &allocator() const noexcept {
1430 return root_.template get<1>();
1431 }
1432
1433 // Allocates a correctly aligned node of at least size bytes using the
1434 // allocator.
1435 node_type *allocate(const size_type size) {
1436 return reinterpret_cast<node_type *>(
1437 absl::container_internal::Allocate<node_type::Alignment()>(
1438 mutable_allocator(), size));
1439 }
1440
1441 // Node creation/deletion routines.
Austin Schuhb4691e92020-12-31 12:37:18 -08001442 node_type *new_internal_node(node_type *parent) {
1443 node_type *n = allocate(node_type::InternalSize());
1444 n->init_internal(parent);
1445 return n;
Austin Schuh36244a12019-09-21 17:52:38 -07001446 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001447 node_type *new_leaf_node(node_type *parent) {
1448 node_type *n = allocate(node_type::LeafSize());
1449 n->init_leaf(parent, kNodeValues);
1450 return n;
Austin Schuh36244a12019-09-21 17:52:38 -07001451 }
1452 node_type *new_leaf_root_node(const int max_count) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001453 node_type *n = allocate(node_type::LeafSize(max_count));
1454 n->init_leaf(/*parent=*/n, max_count);
1455 return n;
Austin Schuh36244a12019-09-21 17:52:38 -07001456 }
1457
1458 // Deletion helper routines.
Austin Schuh36244a12019-09-21 17:52:38 -07001459 iterator rebalance_after_delete(iterator iter);
1460
Austin Schuh36244a12019-09-21 17:52:38 -07001461 // Rebalances or splits the node iter points to.
1462 void rebalance_or_split(iterator *iter);
1463
1464 // Merges the values of left, right and the delimiting key on their parent
1465 // onto left, removing the delimiting key and deleting right.
1466 void merge_nodes(node_type *left, node_type *right);
1467
1468 // Tries to merge node with its left or right sibling, and failing that,
1469 // rebalance with its left or right sibling. Returns true if a merge
1470 // occurred, at which point it is no longer valid to access node. Returns
1471 // false if no merging took place.
1472 bool try_merge_or_rebalance(iterator *iter);
1473
1474 // Tries to shrink the height of the tree by 1.
1475 void try_shrink();
1476
1477 iterator internal_end(iterator iter) {
1478 return iter.node != nullptr ? iter : end();
1479 }
1480 const_iterator internal_end(const_iterator iter) const {
1481 return iter.node != nullptr ? iter : end();
1482 }
1483
1484 // Emplaces a value into the btree immediately before iter. Requires that
1485 // key(v) <= iter.key() and (--iter).key() <= key(v).
1486 template <typename... Args>
1487 iterator internal_emplace(iterator iter, Args &&... args);
1488
1489 // Returns an iterator pointing to the first value >= the value "iter" is
Austin Schuhb4691e92020-12-31 12:37:18 -08001490 // pointing at. Note that "iter" might be pointing to an invalid location such
1491 // as iter.position == iter.node->finish(). This routine simply moves iter up
1492 // in the tree to a valid location.
Austin Schuh36244a12019-09-21 17:52:38 -07001493 // Requires: iter.node is non-null.
1494 template <typename IterType>
1495 static IterType internal_last(IterType iter);
1496
1497 // Returns an iterator pointing to the leaf position at which key would
Austin Schuhb4691e92020-12-31 12:37:18 -08001498 // reside in the tree, unless there is an exact match - in which case, the
1499 // result may not be on a leaf. When there's a three-way comparator, we can
1500 // return whether there was an exact match. This allows the caller to avoid a
1501 // subsequent comparison to determine if an exact match was made, which is
1502 // important for keys with expensive comparison, such as strings.
Austin Schuh36244a12019-09-21 17:52:38 -07001503 template <typename K>
1504 SearchResult<iterator, is_key_compare_to::value> internal_locate(
1505 const K &key) const;
1506
Austin Schuh36244a12019-09-21 17:52:38 -07001507 // Internal routine which implements lower_bound().
1508 template <typename K>
Austin Schuhb4691e92020-12-31 12:37:18 -08001509 SearchResult<iterator, is_key_compare_to::value> internal_lower_bound(
1510 const K &key) const;
Austin Schuh36244a12019-09-21 17:52:38 -07001511
1512 // Internal routine which implements upper_bound().
1513 template <typename K>
1514 iterator internal_upper_bound(const K &key) const;
1515
1516 // Internal routine which implements find().
1517 template <typename K>
1518 iterator internal_find(const K &key) const;
1519
Austin Schuh36244a12019-09-21 17:52:38 -07001520 // Verifies the tree structure of node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001521 int internal_verify(const node_type *node, const key_type *lo,
1522 const key_type *hi) const;
Austin Schuh36244a12019-09-21 17:52:38 -07001523
1524 node_stats internal_stats(const node_type *node) const {
1525 // The root can be a static empty node.
1526 if (node == nullptr || (node == root() && empty())) {
1527 return node_stats(0, 0);
1528 }
1529 if (node->leaf()) {
1530 return node_stats(1, 0);
1531 }
1532 node_stats res(0, 1);
Austin Schuhb4691e92020-12-31 12:37:18 -08001533 for (int i = node->start(); i <= node->finish(); ++i) {
Austin Schuh36244a12019-09-21 17:52:38 -07001534 res += internal_stats(node->child(i));
1535 }
1536 return res;
1537 }
1538
Austin Schuh36244a12019-09-21 17:52:38 -07001539 // We use compressed tuple in order to save space because key_compare and
1540 // allocator_type are usually empty.
1541 absl::container_internal::CompressedTuple<key_compare, allocator_type,
1542 node_type *>
1543 root_;
1544
1545 // A pointer to the rightmost node. Note that the leftmost node is stored as
1546 // the root's parent.
1547 node_type *rightmost_;
1548
1549 // Number of values.
1550 size_type size_;
1551};
1552
1553////
1554// btree_node methods
1555template <typename P>
1556template <typename... Args>
1557inline void btree_node<P>::emplace_value(const size_type i,
1558 allocator_type *alloc,
1559 Args &&... args) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001560 assert(i >= start());
1561 assert(i <= finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001562 // Shift old values to create space for new value and then construct it in
1563 // place.
Austin Schuhb4691e92020-12-31 12:37:18 -08001564 if (i < finish()) {
1565 transfer_n_backward(finish() - i, /*dest_i=*/i + 1, /*src_i=*/i, this,
1566 alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001567 }
1568 value_init(i, alloc, std::forward<Args>(args)...);
Austin Schuhb4691e92020-12-31 12:37:18 -08001569 set_finish(finish() + 1);
Austin Schuh36244a12019-09-21 17:52:38 -07001570
Austin Schuhb4691e92020-12-31 12:37:18 -08001571 if (!leaf() && finish() > i + 1) {
1572 for (int j = finish(); j > i + 1; --j) {
Austin Schuh36244a12019-09-21 17:52:38 -07001573 set_child(j, child(j - 1));
1574 }
1575 clear_child(i + 1);
1576 }
1577}
1578
1579template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08001580inline void btree_node<P>::remove_values(const field_type i,
1581 const field_type to_erase,
1582 allocator_type *alloc) {
1583 // Transfer values after the removed range into their new places.
1584 value_destroy_n(i, to_erase, alloc);
1585 const field_type orig_finish = finish();
1586 const field_type src_i = i + to_erase;
1587 transfer_n(orig_finish - src_i, i, src_i, this, alloc);
1588
1589 if (!leaf()) {
1590 // Delete all children between begin and end.
1591 for (int j = 0; j < to_erase; ++j) {
1592 clear_and_delete(child(i + j + 1), alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001593 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001594 // Rotate children after end into new positions.
1595 for (int j = i + to_erase + 1; j <= orig_finish; ++j) {
1596 set_child(j - to_erase, child(j));
1597 clear_child(j);
1598 }
Austin Schuh36244a12019-09-21 17:52:38 -07001599 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001600 set_finish(orig_finish - to_erase);
Austin Schuh36244a12019-09-21 17:52:38 -07001601}
1602
1603template <typename P>
1604void btree_node<P>::rebalance_right_to_left(const int to_move,
1605 btree_node *right,
1606 allocator_type *alloc) {
1607 assert(parent() == right->parent());
1608 assert(position() + 1 == right->position());
1609 assert(right->count() >= count());
1610 assert(to_move >= 1);
1611 assert(to_move <= right->count());
1612
1613 // 1) Move the delimiting value in the parent to the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001614 transfer(finish(), position(), parent(), alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001615
1616 // 2) Move the (to_move - 1) values from the right node to the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001617 transfer_n(to_move - 1, finish() + 1, right->start(), right, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001618
1619 // 3) Move the new delimiting value to the parent from the right node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001620 parent()->transfer(position(), right->start() + to_move - 1, right, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001621
Austin Schuhb4691e92020-12-31 12:37:18 -08001622 // 4) Shift the values in the right node to their correct positions.
1623 right->transfer_n(right->count() - to_move, right->start(),
1624 right->start() + to_move, right, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001625
1626 if (!leaf()) {
1627 // Move the child pointers from the right to the left node.
1628 for (int i = 0; i < to_move; ++i) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001629 init_child(finish() + i + 1, right->child(i));
Austin Schuh36244a12019-09-21 17:52:38 -07001630 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001631 for (int i = right->start(); i <= right->finish() - to_move; ++i) {
Austin Schuh36244a12019-09-21 17:52:38 -07001632 assert(i + to_move <= right->max_count());
1633 right->init_child(i, right->child(i + to_move));
1634 right->clear_child(i + to_move);
1635 }
1636 }
1637
Austin Schuhb4691e92020-12-31 12:37:18 -08001638 // Fixup `finish` on the left and right nodes.
1639 set_finish(finish() + to_move);
1640 right->set_finish(right->finish() - to_move);
Austin Schuh36244a12019-09-21 17:52:38 -07001641}
1642
1643template <typename P>
1644void btree_node<P>::rebalance_left_to_right(const int to_move,
1645 btree_node *right,
1646 allocator_type *alloc) {
1647 assert(parent() == right->parent());
1648 assert(position() + 1 == right->position());
1649 assert(count() >= right->count());
1650 assert(to_move >= 1);
1651 assert(to_move <= count());
1652
1653 // Values in the right node are shifted to the right to make room for the
1654 // new to_move values. Then, the delimiting value in the parent and the
1655 // other (to_move - 1) values in the left node are moved into the right node.
1656 // Lastly, a new delimiting value is moved from the left node into the
1657 // parent, and the remaining empty left node entries are destroyed.
1658
Austin Schuhb4691e92020-12-31 12:37:18 -08001659 // 1) Shift existing values in the right node to their correct positions.
1660 right->transfer_n_backward(right->count(), right->start() + to_move,
1661 right->start(), right, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001662
Austin Schuhb4691e92020-12-31 12:37:18 -08001663 // 2) Move the delimiting value in the parent to the right node.
1664 right->transfer(right->start() + to_move - 1, position(), parent(), alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001665
Austin Schuhb4691e92020-12-31 12:37:18 -08001666 // 3) Move the (to_move - 1) values from the left node to the right node.
1667 right->transfer_n(to_move - 1, right->start(), finish() - (to_move - 1), this,
1668 alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001669
1670 // 4) Move the new delimiting value to the parent from the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001671 parent()->transfer(position(), finish() - to_move, this, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001672
1673 if (!leaf()) {
1674 // Move the child pointers from the left to the right node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001675 for (int i = right->finish(); i >= right->start(); --i) {
Austin Schuh36244a12019-09-21 17:52:38 -07001676 right->init_child(i + to_move, right->child(i));
1677 right->clear_child(i);
1678 }
1679 for (int i = 1; i <= to_move; ++i) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001680 right->init_child(i - 1, child(finish() - to_move + i));
1681 clear_child(finish() - to_move + i);
Austin Schuh36244a12019-09-21 17:52:38 -07001682 }
1683 }
1684
1685 // Fixup the counts on the left and right nodes.
Austin Schuhb4691e92020-12-31 12:37:18 -08001686 set_finish(finish() - to_move);
1687 right->set_finish(right->finish() + to_move);
Austin Schuh36244a12019-09-21 17:52:38 -07001688}
1689
1690template <typename P>
1691void btree_node<P>::split(const int insert_position, btree_node *dest,
1692 allocator_type *alloc) {
1693 assert(dest->count() == 0);
1694 assert(max_count() == kNodeValues);
1695
1696 // We bias the split based on the position being inserted. If we're
1697 // inserting at the beginning of the left node then bias the split to put
1698 // more values on the right node. If we're inserting at the end of the
1699 // right node then bias the split to put more values on the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001700 if (insert_position == start()) {
1701 dest->set_finish(dest->start() + finish() - 1);
Austin Schuh36244a12019-09-21 17:52:38 -07001702 } else if (insert_position == kNodeValues) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001703 dest->set_finish(dest->start());
Austin Schuh36244a12019-09-21 17:52:38 -07001704 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08001705 dest->set_finish(dest->start() + count() / 2);
Austin Schuh36244a12019-09-21 17:52:38 -07001706 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001707 set_finish(finish() - dest->count());
Austin Schuh36244a12019-09-21 17:52:38 -07001708 assert(count() >= 1);
1709
1710 // Move values from the left sibling to the right sibling.
Austin Schuhb4691e92020-12-31 12:37:18 -08001711 dest->transfer_n(dest->count(), dest->start(), finish(), this, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001712
1713 // The split key is the largest value in the left sibling.
Austin Schuhb4691e92020-12-31 12:37:18 -08001714 --mutable_finish();
1715 parent()->emplace_value(position(), alloc, finish_slot());
1716 value_destroy(finish(), alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001717 parent()->init_child(position() + 1, dest);
1718
1719 if (!leaf()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001720 for (int i = dest->start(), j = finish() + 1; i <= dest->finish();
1721 ++i, ++j) {
1722 assert(child(j) != nullptr);
1723 dest->init_child(i, child(j));
1724 clear_child(j);
Austin Schuh36244a12019-09-21 17:52:38 -07001725 }
1726 }
1727}
1728
1729template <typename P>
1730void btree_node<P>::merge(btree_node *src, allocator_type *alloc) {
1731 assert(parent() == src->parent());
1732 assert(position() + 1 == src->position());
1733
1734 // Move the delimiting value to the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001735 value_init(finish(), alloc, parent()->slot(position()));
Austin Schuh36244a12019-09-21 17:52:38 -07001736
1737 // Move the values from the right to the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001738 transfer_n(src->count(), finish() + 1, src->start(), src, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001739
1740 if (!leaf()) {
1741 // Move the child pointers from the right to the left node.
Austin Schuhb4691e92020-12-31 12:37:18 -08001742 for (int i = src->start(), j = finish() + 1; i <= src->finish(); ++i, ++j) {
1743 init_child(j, src->child(i));
Austin Schuh36244a12019-09-21 17:52:38 -07001744 src->clear_child(i);
1745 }
1746 }
1747
Austin Schuhb4691e92020-12-31 12:37:18 -08001748 // Fixup `finish` on the src and dest nodes.
1749 set_finish(start() + 1 + count() + src->count());
1750 src->set_finish(src->start());
Austin Schuh36244a12019-09-21 17:52:38 -07001751
Austin Schuhb4691e92020-12-31 12:37:18 -08001752 // Remove the value on the parent node and delete the src node.
1753 parent()->remove_values(position(), /*to_erase=*/1, alloc);
Austin Schuh36244a12019-09-21 17:52:38 -07001754}
1755
1756template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08001757void btree_node<P>::clear_and_delete(btree_node *node, allocator_type *alloc) {
1758 if (node->leaf()) {
1759 node->value_destroy_n(node->start(), node->count(), alloc);
1760 deallocate(LeafSize(node->max_count()), node, alloc);
1761 return;
1762 }
1763 if (node->count() == 0) {
1764 deallocate(InternalSize(), node, alloc);
1765 return;
Austin Schuh36244a12019-09-21 17:52:38 -07001766 }
1767
Austin Schuhb4691e92020-12-31 12:37:18 -08001768 // The parent of the root of the subtree we are deleting.
1769 btree_node *delete_root_parent = node->parent();
1770
1771 // Navigate to the leftmost leaf under node, and then delete upwards.
1772 while (!node->leaf()) node = node->start_child();
1773 // Use `int` because `pos` needs to be able to hold `kNodeValues+1`, which
1774 // isn't guaranteed to be a valid `field_type`.
1775 int pos = node->position();
1776 btree_node *parent = node->parent();
1777 for (;;) {
1778 // In each iteration of the next loop, we delete one leaf node and go right.
1779 assert(pos <= parent->finish());
1780 do {
1781 node = parent->child(pos);
1782 if (!node->leaf()) {
1783 // Navigate to the leftmost leaf under node.
1784 while (!node->leaf()) node = node->start_child();
1785 pos = node->position();
1786 parent = node->parent();
1787 }
1788 node->value_destroy_n(node->start(), node->count(), alloc);
1789 deallocate(LeafSize(node->max_count()), node, alloc);
1790 ++pos;
1791 } while (pos <= parent->finish());
1792
1793 // Once we've deleted all children of parent, delete parent and go up/right.
1794 assert(pos > parent->finish());
1795 do {
1796 node = parent;
1797 pos = node->position();
1798 parent = node->parent();
1799 node->value_destroy_n(node->start(), node->count(), alloc);
1800 deallocate(InternalSize(), node, alloc);
1801 if (parent == delete_root_parent) return;
1802 ++pos;
1803 } while (pos > parent->finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001804 }
Austin Schuh36244a12019-09-21 17:52:38 -07001805}
1806
1807////
1808// btree_iterator methods
1809template <typename N, typename R, typename P>
1810void btree_iterator<N, R, P>::increment_slow() {
1811 if (node->leaf()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001812 assert(position >= node->finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001813 btree_iterator save(*this);
Austin Schuhb4691e92020-12-31 12:37:18 -08001814 while (position == node->finish() && !node->is_root()) {
Austin Schuh36244a12019-09-21 17:52:38 -07001815 assert(node->parent()->child(node->position()) == node);
1816 position = node->position();
1817 node = node->parent();
1818 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001819 // TODO(ezb): assert we aren't incrementing end() instead of handling.
1820 if (position == node->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07001821 *this = save;
1822 }
1823 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08001824 assert(position < node->finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001825 node = node->child(position + 1);
1826 while (!node->leaf()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001827 node = node->start_child();
Austin Schuh36244a12019-09-21 17:52:38 -07001828 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001829 position = node->start();
Austin Schuh36244a12019-09-21 17:52:38 -07001830 }
1831}
1832
1833template <typename N, typename R, typename P>
1834void btree_iterator<N, R, P>::decrement_slow() {
1835 if (node->leaf()) {
1836 assert(position <= -1);
1837 btree_iterator save(*this);
Austin Schuhb4691e92020-12-31 12:37:18 -08001838 while (position < node->start() && !node->is_root()) {
Austin Schuh36244a12019-09-21 17:52:38 -07001839 assert(node->parent()->child(node->position()) == node);
1840 position = node->position() - 1;
1841 node = node->parent();
1842 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001843 // TODO(ezb): assert we aren't decrementing begin() instead of handling.
1844 if (position < node->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -07001845 *this = save;
1846 }
1847 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08001848 assert(position >= node->start());
Austin Schuh36244a12019-09-21 17:52:38 -07001849 node = node->child(position);
1850 while (!node->leaf()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001851 node = node->child(node->finish());
Austin Schuh36244a12019-09-21 17:52:38 -07001852 }
Austin Schuhb4691e92020-12-31 12:37:18 -08001853 position = node->finish() - 1;
Austin Schuh36244a12019-09-21 17:52:38 -07001854 }
1855}
1856
1857////
1858// btree methods
1859template <typename P>
1860template <typename Btree>
Austin Schuhb4691e92020-12-31 12:37:18 -08001861void btree<P>::copy_or_move_values_in_order(Btree &other) {
Austin Schuh36244a12019-09-21 17:52:38 -07001862 static_assert(std::is_same<btree, Btree>::value ||
1863 std::is_same<const btree, Btree>::value,
1864 "Btree type must be same or const.");
1865 assert(empty());
1866
1867 // We can avoid key comparisons because we know the order of the
1868 // values is the same order we'll store them in.
Austin Schuhb4691e92020-12-31 12:37:18 -08001869 auto iter = other.begin();
1870 if (iter == other.end()) return;
Austin Schuh36244a12019-09-21 17:52:38 -07001871 insert_multi(maybe_move_from_iterator(iter));
1872 ++iter;
Austin Schuhb4691e92020-12-31 12:37:18 -08001873 for (; iter != other.end(); ++iter) {
Austin Schuh36244a12019-09-21 17:52:38 -07001874 // If the btree is not empty, we can just insert the new value at the end
1875 // of the tree.
1876 internal_emplace(end(), maybe_move_from_iterator(iter));
1877 }
1878}
1879
1880template <typename P>
1881constexpr bool btree<P>::static_assert_validation() {
1882 static_assert(std::is_nothrow_copy_constructible<key_compare>::value,
1883 "Key comparison must be nothrow copy constructible");
1884 static_assert(std::is_nothrow_copy_constructible<allocator_type>::value,
1885 "Allocator must be nothrow copy constructible");
1886 static_assert(type_traits_internal::is_trivially_copyable<iterator>::value,
1887 "iterator not trivially copyable.");
1888
1889 // Note: We assert that kTargetValues, which is computed from
1890 // Params::kTargetNodeSize, must fit the node_type::field_type.
1891 static_assert(
1892 kNodeValues < (1 << (8 * sizeof(typename node_type::field_type))),
1893 "target node size too large");
1894
1895 // Verify that key_compare returns an absl::{weak,strong}_ordering or bool.
1896 using compare_result_type =
1897 absl::result_of_t<key_compare(key_type, key_type)>;
1898 static_assert(
1899 std::is_same<compare_result_type, bool>::value ||
1900 std::is_convertible<compare_result_type, absl::weak_ordering>::value,
1901 "key comparison function must return absl::{weak,strong}_ordering or "
1902 "bool.");
1903
1904 // Test the assumption made in setting kNodeValueSpace.
1905 static_assert(node_type::MinimumOverhead() >= sizeof(void *) + 4,
1906 "node space assumption incorrect");
1907
1908 return true;
1909}
1910
1911template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08001912template <typename K>
1913auto btree<P>::lower_bound_equal(const K &key) const
1914 -> std::pair<iterator, bool> {
1915 const SearchResult<iterator, is_key_compare_to::value> res =
1916 internal_lower_bound(key);
1917 const iterator lower = iterator(internal_end(res.value));
1918 const bool equal = res.HasMatch()
1919 ? res.IsEq()
1920 : lower != end() && !compare_keys(key, lower.key());
1921 return {lower, equal};
Austin Schuh36244a12019-09-21 17:52:38 -07001922}
1923
1924template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08001925template <typename K>
1926auto btree<P>::equal_range(const K &key) -> std::pair<iterator, iterator> {
1927 const std::pair<iterator, bool> lower_and_equal = lower_bound_equal(key);
1928 const iterator lower = lower_and_equal.first;
1929 if (!lower_and_equal.second) {
1930 return {lower, lower};
1931 }
1932
1933 const iterator next = std::next(lower);
1934 if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
1935 // The next iterator after lower must point to a key greater than `key`.
1936 // Note: if this assert fails, then it may indicate that the comparator does
1937 // not meet the equivalence requirements for Compare
1938 // (see https://en.cppreference.com/w/cpp/named_req/Compare).
1939 assert(next == end() || compare_keys(key, next.key()));
1940 return {lower, next};
1941 }
1942 // Try once more to avoid the call to upper_bound() if there's only one
1943 // equivalent key. This should prevent all calls to upper_bound() in cases of
1944 // unique-containers with heterogeneous comparators in which all comparison
1945 // operators have the same equivalence classes.
1946 if (next == end() || compare_keys(key, next.key())) return {lower, next};
1947
1948 // In this case, we need to call upper_bound() to avoid worst case O(N)
1949 // behavior if we were to iterate over equal keys.
1950 return {lower, upper_bound(key)};
1951}
1952
1953template <typename P>
1954template <typename K, typename... Args>
1955auto btree<P>::insert_unique(const K &key, Args &&... args)
Austin Schuh36244a12019-09-21 17:52:38 -07001956 -> std::pair<iterator, bool> {
1957 if (empty()) {
1958 mutable_root() = rightmost_ = new_leaf_root_node(1);
1959 }
1960
Austin Schuhb4691e92020-12-31 12:37:18 -08001961 SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
1962 iterator iter = res.value;
Austin Schuh36244a12019-09-21 17:52:38 -07001963
1964 if (res.HasMatch()) {
1965 if (res.IsEq()) {
1966 // The key already exists in the tree, do nothing.
1967 return {iter, false};
1968 }
1969 } else {
1970 iterator last = internal_last(iter);
1971 if (last.node && !compare_keys(key, last.key())) {
1972 // The key already exists in the tree, do nothing.
1973 return {last, false};
1974 }
1975 }
1976 return {internal_emplace(iter, std::forward<Args>(args)...), true};
1977}
1978
1979template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08001980template <typename K, typename... Args>
1981inline auto btree<P>::insert_hint_unique(iterator position, const K &key,
Austin Schuh36244a12019-09-21 17:52:38 -07001982 Args &&... args)
1983 -> std::pair<iterator, bool> {
1984 if (!empty()) {
1985 if (position == end() || compare_keys(key, position.key())) {
Austin Schuhb4691e92020-12-31 12:37:18 -08001986 if (position == begin() || compare_keys(std::prev(position).key(), key)) {
Austin Schuh36244a12019-09-21 17:52:38 -07001987 // prev.key() < key < position.key()
1988 return {internal_emplace(position, std::forward<Args>(args)...), true};
1989 }
1990 } else if (compare_keys(position.key(), key)) {
1991 ++position;
1992 if (position == end() || compare_keys(key, position.key())) {
1993 // {original `position`}.key() < key < {current `position`}.key()
1994 return {internal_emplace(position, std::forward<Args>(args)...), true};
1995 }
1996 } else {
1997 // position.key() == key
1998 return {position, false};
1999 }
2000 }
2001 return insert_unique(key, std::forward<Args>(args)...);
2002}
2003
2004template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002005template <typename InputIterator, typename>
2006void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, int) {
Austin Schuh36244a12019-09-21 17:52:38 -07002007 for (; b != e; ++b) {
2008 insert_hint_unique(end(), params_type::key(*b), *b);
2009 }
2010}
2011
2012template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002013template <typename InputIterator>
2014void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e, char) {
2015 for (; b != e; ++b) {
2016 init_type value(*b);
2017 insert_hint_unique(end(), params_type::key(value), std::move(value));
2018 }
2019}
2020
2021template <typename P>
Austin Schuh36244a12019-09-21 17:52:38 -07002022template <typename ValueType>
2023auto btree<P>::insert_multi(const key_type &key, ValueType &&v) -> iterator {
2024 if (empty()) {
2025 mutable_root() = rightmost_ = new_leaf_root_node(1);
2026 }
2027
2028 iterator iter = internal_upper_bound(key);
2029 if (iter.node == nullptr) {
2030 iter = end();
2031 }
2032 return internal_emplace(iter, std::forward<ValueType>(v));
2033}
2034
2035template <typename P>
2036template <typename ValueType>
2037auto btree<P>::insert_hint_multi(iterator position, ValueType &&v) -> iterator {
2038 if (!empty()) {
2039 const key_type &key = params_type::key(v);
2040 if (position == end() || !compare_keys(position.key(), key)) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002041 if (position == begin() ||
2042 !compare_keys(key, std::prev(position).key())) {
Austin Schuh36244a12019-09-21 17:52:38 -07002043 // prev.key() <= key <= position.key()
2044 return internal_emplace(position, std::forward<ValueType>(v));
2045 }
2046 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08002047 ++position;
2048 if (position == end() || !compare_keys(position.key(), key)) {
2049 // {original `position`}.key() < key < {current `position`}.key()
2050 return internal_emplace(position, std::forward<ValueType>(v));
Austin Schuh36244a12019-09-21 17:52:38 -07002051 }
2052 }
2053 }
2054 return insert_multi(std::forward<ValueType>(v));
2055}
2056
2057template <typename P>
2058template <typename InputIterator>
2059void btree<P>::insert_iterator_multi(InputIterator b, InputIterator e) {
2060 for (; b != e; ++b) {
2061 insert_hint_multi(end(), *b);
2062 }
2063}
2064
2065template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002066auto btree<P>::operator=(const btree &other) -> btree & {
2067 if (this != &other) {
Austin Schuh36244a12019-09-21 17:52:38 -07002068 clear();
2069
Austin Schuhb4691e92020-12-31 12:37:18 -08002070 *mutable_key_comp() = other.key_comp();
Austin Schuh36244a12019-09-21 17:52:38 -07002071 if (absl::allocator_traits<
2072 allocator_type>::propagate_on_container_copy_assignment::value) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002073 *mutable_allocator() = other.allocator();
Austin Schuh36244a12019-09-21 17:52:38 -07002074 }
2075
Austin Schuhb4691e92020-12-31 12:37:18 -08002076 copy_or_move_values_in_order(other);
Austin Schuh36244a12019-09-21 17:52:38 -07002077 }
2078 return *this;
2079}
2080
2081template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002082auto btree<P>::operator=(btree &&other) noexcept -> btree & {
2083 if (this != &other) {
Austin Schuh36244a12019-09-21 17:52:38 -07002084 clear();
2085
2086 using std::swap;
2087 if (absl::allocator_traits<
2088 allocator_type>::propagate_on_container_copy_assignment::value) {
2089 // Note: `root_` also contains the allocator and the key comparator.
Austin Schuhb4691e92020-12-31 12:37:18 -08002090 swap(root_, other.root_);
2091 swap(rightmost_, other.rightmost_);
2092 swap(size_, other.size_);
Austin Schuh36244a12019-09-21 17:52:38 -07002093 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08002094 if (allocator() == other.allocator()) {
2095 swap(mutable_root(), other.mutable_root());
2096 swap(*mutable_key_comp(), *other.mutable_key_comp());
2097 swap(rightmost_, other.rightmost_);
2098 swap(size_, other.size_);
Austin Schuh36244a12019-09-21 17:52:38 -07002099 } else {
2100 // We aren't allowed to propagate the allocator and the allocator is
2101 // different so we can't take over its memory. We must move each element
Austin Schuhb4691e92020-12-31 12:37:18 -08002102 // individually. We need both `other` and `this` to have `other`s key
2103 // comparator while moving the values so we can't swap the key
2104 // comparators.
2105 *mutable_key_comp() = other.key_comp();
2106 copy_or_move_values_in_order(other);
Austin Schuh36244a12019-09-21 17:52:38 -07002107 }
2108 }
2109 }
2110 return *this;
2111}
2112
2113template <typename P>
2114auto btree<P>::erase(iterator iter) -> iterator {
2115 bool internal_delete = false;
2116 if (!iter.node->leaf()) {
2117 // Deletion of a value on an internal node. First, move the largest value
Austin Schuhb4691e92020-12-31 12:37:18 -08002118 // from our left child here, then delete that position (in remove_values()
Austin Schuh36244a12019-09-21 17:52:38 -07002119 // below). We can get to the largest value from our left child by
2120 // decrementing iter.
2121 iterator internal_iter(iter);
2122 --iter;
2123 assert(iter.node->leaf());
Austin Schuh36244a12019-09-21 17:52:38 -07002124 params_type::move(mutable_allocator(), iter.node->slot(iter.position),
2125 internal_iter.node->slot(internal_iter.position));
2126 internal_delete = true;
2127 }
2128
2129 // Delete the key from the leaf.
Austin Schuhb4691e92020-12-31 12:37:18 -08002130 iter.node->remove_values(iter.position, /*to_erase=*/1, mutable_allocator());
Austin Schuh36244a12019-09-21 17:52:38 -07002131 --size_;
2132
2133 // We want to return the next value after the one we just erased. If we
2134 // erased from an internal node (internal_delete == true), then the next
2135 // value is ++(++iter). If we erased from a leaf node (internal_delete ==
2136 // false) then the next value is ++iter. Note that ++iter may point to an
2137 // internal node and the value in the internal node may move to a leaf node
2138 // (iter.node) when rebalancing is performed at the leaf level.
2139
2140 iterator res = rebalance_after_delete(iter);
2141
2142 // If we erased from an internal node, advance the iterator.
2143 if (internal_delete) {
2144 ++res;
2145 }
2146 return res;
2147}
2148
2149template <typename P>
2150auto btree<P>::rebalance_after_delete(iterator iter) -> iterator {
2151 // Merge/rebalance as we walk back up the tree.
2152 iterator res(iter);
2153 bool first_iteration = true;
2154 for (;;) {
2155 if (iter.node == root()) {
2156 try_shrink();
2157 if (empty()) {
2158 return end();
2159 }
2160 break;
2161 }
2162 if (iter.node->count() >= kMinNodeValues) {
2163 break;
2164 }
2165 bool merged = try_merge_or_rebalance(&iter);
2166 // On the first iteration, we should update `res` with `iter` because `res`
2167 // may have been invalidated.
2168 if (first_iteration) {
2169 res = iter;
2170 first_iteration = false;
2171 }
2172 if (!merged) {
2173 break;
2174 }
2175 iter.position = iter.node->position();
2176 iter.node = iter.node->parent();
2177 }
2178
2179 // Adjust our return value. If we're pointing at the end of a node, advance
2180 // the iterator.
Austin Schuhb4691e92020-12-31 12:37:18 -08002181 if (res.position == res.node->finish()) {
2182 res.position = res.node->finish() - 1;
Austin Schuh36244a12019-09-21 17:52:38 -07002183 ++res;
2184 }
2185
2186 return res;
2187}
2188
2189template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002190auto btree<P>::erase_range(iterator begin, iterator end)
Austin Schuh36244a12019-09-21 17:52:38 -07002191 -> std::pair<size_type, iterator> {
2192 difference_type count = std::distance(begin, end);
2193 assert(count >= 0);
2194
2195 if (count == 0) {
2196 return {0, begin};
2197 }
2198
2199 if (count == size_) {
2200 clear();
2201 return {count, this->end()};
2202 }
2203
2204 if (begin.node == end.node) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002205 assert(end.position > begin.position);
2206 begin.node->remove_values(begin.position, end.position - begin.position,
2207 mutable_allocator());
Austin Schuh36244a12019-09-21 17:52:38 -07002208 size_ -= count;
2209 return {count, rebalance_after_delete(begin)};
2210 }
2211
2212 const size_type target_size = size_ - count;
2213 while (size_ > target_size) {
2214 if (begin.node->leaf()) {
2215 const size_type remaining_to_erase = size_ - target_size;
Austin Schuhb4691e92020-12-31 12:37:18 -08002216 const size_type remaining_in_node = begin.node->finish() - begin.position;
2217 const size_type to_erase =
2218 (std::min)(remaining_to_erase, remaining_in_node);
2219 begin.node->remove_values(begin.position, to_erase, mutable_allocator());
2220 size_ -= to_erase;
2221 begin = rebalance_after_delete(begin);
Austin Schuh36244a12019-09-21 17:52:38 -07002222 } else {
2223 begin = erase(begin);
2224 }
2225 }
2226 return {count, begin};
2227}
2228
2229template <typename P>
Austin Schuh36244a12019-09-21 17:52:38 -07002230void btree<P>::clear() {
2231 if (!empty()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002232 node_type::clear_and_delete(root(), mutable_allocator());
Austin Schuh36244a12019-09-21 17:52:38 -07002233 }
2234 mutable_root() = EmptyNode();
2235 rightmost_ = EmptyNode();
2236 size_ = 0;
2237}
2238
2239template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002240void btree<P>::swap(btree &other) {
Austin Schuh36244a12019-09-21 17:52:38 -07002241 using std::swap;
2242 if (absl::allocator_traits<
2243 allocator_type>::propagate_on_container_swap::value) {
2244 // Note: `root_` also contains the allocator and the key comparator.
Austin Schuhb4691e92020-12-31 12:37:18 -08002245 swap(root_, other.root_);
Austin Schuh36244a12019-09-21 17:52:38 -07002246 } else {
2247 // It's undefined behavior if the allocators are unequal here.
Austin Schuhb4691e92020-12-31 12:37:18 -08002248 assert(allocator() == other.allocator());
2249 swap(mutable_root(), other.mutable_root());
2250 swap(*mutable_key_comp(), *other.mutable_key_comp());
Austin Schuh36244a12019-09-21 17:52:38 -07002251 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002252 swap(rightmost_, other.rightmost_);
2253 swap(size_, other.size_);
Austin Schuh36244a12019-09-21 17:52:38 -07002254}
2255
2256template <typename P>
2257void btree<P>::verify() const {
2258 assert(root() != nullptr);
2259 assert(leftmost() != nullptr);
2260 assert(rightmost_ != nullptr);
2261 assert(empty() || size() == internal_verify(root(), nullptr, nullptr));
2262 assert(leftmost() == (++const_iterator(root(), -1)).node);
Austin Schuhb4691e92020-12-31 12:37:18 -08002263 assert(rightmost_ == (--const_iterator(root(), root()->finish())).node);
Austin Schuh36244a12019-09-21 17:52:38 -07002264 assert(leftmost()->leaf());
2265 assert(rightmost_->leaf());
2266}
2267
2268template <typename P>
2269void btree<P>::rebalance_or_split(iterator *iter) {
2270 node_type *&node = iter->node;
2271 int &insert_position = iter->position;
2272 assert(node->count() == node->max_count());
2273 assert(kNodeValues == node->max_count());
2274
2275 // First try to make room on the node by rebalancing.
2276 node_type *parent = node->parent();
2277 if (node != root()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002278 if (node->position() > parent->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002279 // Try rebalancing with our left sibling.
2280 node_type *left = parent->child(node->position() - 1);
2281 assert(left->max_count() == kNodeValues);
2282 if (left->count() < kNodeValues) {
2283 // We bias rebalancing based on the position being inserted. If we're
2284 // inserting at the end of the right node then we bias rebalancing to
2285 // fill up the left node.
2286 int to_move = (kNodeValues - left->count()) /
Austin Schuhb4691e92020-12-31 12:37:18 -08002287 (1 + (insert_position < static_cast<int>(kNodeValues)));
Austin Schuh36244a12019-09-21 17:52:38 -07002288 to_move = (std::max)(1, to_move);
2289
Austin Schuhb4691e92020-12-31 12:37:18 -08002290 if (insert_position - to_move >= node->start() ||
2291 left->count() + to_move < static_cast<int>(kNodeValues)) {
Austin Schuh36244a12019-09-21 17:52:38 -07002292 left->rebalance_right_to_left(to_move, node, mutable_allocator());
2293
2294 assert(node->max_count() - node->count() == to_move);
2295 insert_position = insert_position - to_move;
Austin Schuhb4691e92020-12-31 12:37:18 -08002296 if (insert_position < node->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002297 insert_position = insert_position + left->count() + 1;
2298 node = left;
2299 }
2300
2301 assert(node->count() < node->max_count());
2302 return;
2303 }
2304 }
2305 }
2306
Austin Schuhb4691e92020-12-31 12:37:18 -08002307 if (node->position() < parent->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002308 // Try rebalancing with our right sibling.
2309 node_type *right = parent->child(node->position() + 1);
2310 assert(right->max_count() == kNodeValues);
2311 if (right->count() < kNodeValues) {
2312 // We bias rebalancing based on the position being inserted. If we're
2313 // inserting at the beginning of the left node then we bias rebalancing
2314 // to fill up the right node.
Austin Schuhb4691e92020-12-31 12:37:18 -08002315 int to_move = (static_cast<int>(kNodeValues) - right->count()) /
2316 (1 + (insert_position > node->start()));
Austin Schuh36244a12019-09-21 17:52:38 -07002317 to_move = (std::max)(1, to_move);
2318
Austin Schuhb4691e92020-12-31 12:37:18 -08002319 if (insert_position <= node->finish() - to_move ||
2320 right->count() + to_move < static_cast<int>(kNodeValues)) {
Austin Schuh36244a12019-09-21 17:52:38 -07002321 node->rebalance_left_to_right(to_move, right, mutable_allocator());
2322
Austin Schuhb4691e92020-12-31 12:37:18 -08002323 if (insert_position > node->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002324 insert_position = insert_position - node->count() - 1;
2325 node = right;
2326 }
2327
2328 assert(node->count() < node->max_count());
2329 return;
2330 }
2331 }
2332 }
2333
2334 // Rebalancing failed, make sure there is room on the parent node for a new
2335 // value.
2336 assert(parent->max_count() == kNodeValues);
2337 if (parent->count() == kNodeValues) {
2338 iterator parent_iter(node->parent(), node->position());
2339 rebalance_or_split(&parent_iter);
2340 }
2341 } else {
2342 // Rebalancing not possible because this is the root node.
2343 // Create a new root node and set the current root node as the child of the
2344 // new root.
2345 parent = new_internal_node(parent);
Austin Schuhb4691e92020-12-31 12:37:18 -08002346 parent->init_child(parent->start(), root());
Austin Schuh36244a12019-09-21 17:52:38 -07002347 mutable_root() = parent;
2348 // If the former root was a leaf node, then it's now the rightmost node.
Austin Schuhb4691e92020-12-31 12:37:18 -08002349 assert(!parent->start_child()->leaf() ||
2350 parent->start_child() == rightmost_);
Austin Schuh36244a12019-09-21 17:52:38 -07002351 }
2352
2353 // Split the node.
2354 node_type *split_node;
2355 if (node->leaf()) {
2356 split_node = new_leaf_node(parent);
2357 node->split(insert_position, split_node, mutable_allocator());
2358 if (rightmost_ == node) rightmost_ = split_node;
2359 } else {
2360 split_node = new_internal_node(parent);
2361 node->split(insert_position, split_node, mutable_allocator());
2362 }
2363
Austin Schuhb4691e92020-12-31 12:37:18 -08002364 if (insert_position > node->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002365 insert_position = insert_position - node->count() - 1;
2366 node = split_node;
2367 }
2368}
2369
2370template <typename P>
2371void btree<P>::merge_nodes(node_type *left, node_type *right) {
2372 left->merge(right, mutable_allocator());
Austin Schuhb4691e92020-12-31 12:37:18 -08002373 if (rightmost_ == right) rightmost_ = left;
Austin Schuh36244a12019-09-21 17:52:38 -07002374}
2375
2376template <typename P>
2377bool btree<P>::try_merge_or_rebalance(iterator *iter) {
2378 node_type *parent = iter->node->parent();
Austin Schuhb4691e92020-12-31 12:37:18 -08002379 if (iter->node->position() > parent->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002380 // Try merging with our left sibling.
2381 node_type *left = parent->child(iter->node->position() - 1);
2382 assert(left->max_count() == kNodeValues);
Austin Schuhb4691e92020-12-31 12:37:18 -08002383 if (1U + left->count() + iter->node->count() <= kNodeValues) {
Austin Schuh36244a12019-09-21 17:52:38 -07002384 iter->position += 1 + left->count();
2385 merge_nodes(left, iter->node);
2386 iter->node = left;
2387 return true;
2388 }
2389 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002390 if (iter->node->position() < parent->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002391 // Try merging with our right sibling.
2392 node_type *right = parent->child(iter->node->position() + 1);
2393 assert(right->max_count() == kNodeValues);
Austin Schuhb4691e92020-12-31 12:37:18 -08002394 if (1U + iter->node->count() + right->count() <= kNodeValues) {
Austin Schuh36244a12019-09-21 17:52:38 -07002395 merge_nodes(iter->node, right);
2396 return true;
2397 }
2398 // Try rebalancing with our right sibling. We don't perform rebalancing if
2399 // we deleted the first element from iter->node and the node is not
2400 // empty. This is a small optimization for the common pattern of deleting
2401 // from the front of the tree.
Austin Schuhb4691e92020-12-31 12:37:18 -08002402 if (right->count() > kMinNodeValues &&
2403 (iter->node->count() == 0 || iter->position > iter->node->start())) {
Austin Schuh36244a12019-09-21 17:52:38 -07002404 int to_move = (right->count() - iter->node->count()) / 2;
2405 to_move = (std::min)(to_move, right->count() - 1);
2406 iter->node->rebalance_right_to_left(to_move, right, mutable_allocator());
2407 return false;
2408 }
2409 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002410 if (iter->node->position() > parent->start()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002411 // Try rebalancing with our left sibling. We don't perform rebalancing if
2412 // we deleted the last element from iter->node and the node is not
2413 // empty. This is a small optimization for the common pattern of deleting
2414 // from the back of the tree.
2415 node_type *left = parent->child(iter->node->position() - 1);
Austin Schuhb4691e92020-12-31 12:37:18 -08002416 if (left->count() > kMinNodeValues &&
2417 (iter->node->count() == 0 || iter->position < iter->node->finish())) {
Austin Schuh36244a12019-09-21 17:52:38 -07002418 int to_move = (left->count() - iter->node->count()) / 2;
2419 to_move = (std::min)(to_move, left->count() - 1);
2420 left->rebalance_left_to_right(to_move, iter->node, mutable_allocator());
2421 iter->position += to_move;
2422 return false;
2423 }
2424 }
2425 return false;
2426}
2427
2428template <typename P>
2429void btree<P>::try_shrink() {
Austin Schuhb4691e92020-12-31 12:37:18 -08002430 node_type *orig_root = root();
2431 if (orig_root->count() > 0) {
Austin Schuh36244a12019-09-21 17:52:38 -07002432 return;
2433 }
2434 // Deleted the last item on the root node, shrink the height of the tree.
Austin Schuhb4691e92020-12-31 12:37:18 -08002435 if (orig_root->leaf()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002436 assert(size() == 0);
Austin Schuhb4691e92020-12-31 12:37:18 -08002437 mutable_root() = rightmost_ = EmptyNode();
Austin Schuh36244a12019-09-21 17:52:38 -07002438 } else {
Austin Schuhb4691e92020-12-31 12:37:18 -08002439 node_type *child = orig_root->start_child();
Austin Schuh36244a12019-09-21 17:52:38 -07002440 child->make_root();
Austin Schuh36244a12019-09-21 17:52:38 -07002441 mutable_root() = child;
2442 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002443 node_type::clear_and_delete(orig_root, mutable_allocator());
Austin Schuh36244a12019-09-21 17:52:38 -07002444}
2445
2446template <typename P>
2447template <typename IterType>
2448inline IterType btree<P>::internal_last(IterType iter) {
2449 assert(iter.node != nullptr);
Austin Schuhb4691e92020-12-31 12:37:18 -08002450 while (iter.position == iter.node->finish()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002451 iter.position = iter.node->position();
2452 iter.node = iter.node->parent();
2453 if (iter.node->leaf()) {
2454 iter.node = nullptr;
2455 break;
2456 }
2457 }
2458 return iter;
2459}
2460
2461template <typename P>
2462template <typename... Args>
2463inline auto btree<P>::internal_emplace(iterator iter, Args &&... args)
2464 -> iterator {
2465 if (!iter.node->leaf()) {
2466 // We can't insert on an internal node. Instead, we'll insert after the
2467 // previous value which is guaranteed to be on a leaf node.
2468 --iter;
2469 ++iter.position;
2470 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002471 const field_type max_count = iter.node->max_count();
2472 allocator_type *alloc = mutable_allocator();
Austin Schuh36244a12019-09-21 17:52:38 -07002473 if (iter.node->count() == max_count) {
2474 // Make room in the leaf for the new item.
2475 if (max_count < kNodeValues) {
2476 // Insertion into the root where the root is smaller than the full node
2477 // size. Simply grow the size of the root node.
2478 assert(iter.node == root());
2479 iter.node =
2480 new_leaf_root_node((std::min<int>)(kNodeValues, 2 * max_count));
Austin Schuhb4691e92020-12-31 12:37:18 -08002481 // Transfer the values from the old root to the new root.
2482 node_type *old_root = root();
2483 node_type *new_root = iter.node;
2484 new_root->transfer_n(old_root->count(), new_root->start(),
2485 old_root->start(), old_root, alloc);
2486 new_root->set_finish(old_root->finish());
2487 old_root->set_finish(old_root->start());
2488 node_type::clear_and_delete(old_root, alloc);
2489 mutable_root() = rightmost_ = new_root;
Austin Schuh36244a12019-09-21 17:52:38 -07002490 } else {
2491 rebalance_or_split(&iter);
2492 }
2493 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002494 iter.node->emplace_value(iter.position, alloc, std::forward<Args>(args)...);
Austin Schuh36244a12019-09-21 17:52:38 -07002495 ++size_;
2496 return iter;
2497}
2498
2499template <typename P>
2500template <typename K>
2501inline auto btree<P>::internal_locate(const K &key) const
2502 -> SearchResult<iterator, is_key_compare_to::value> {
Austin Schuhb4691e92020-12-31 12:37:18 -08002503 iterator iter(const_cast<node_type *>(root()));
Austin Schuh36244a12019-09-21 17:52:38 -07002504 for (;;) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002505 SearchResult<int, is_key_compare_to::value> res =
2506 iter.node->lower_bound(key, key_comp());
Austin Schuh36244a12019-09-21 17:52:38 -07002507 iter.position = res.value;
Austin Schuhb4691e92020-12-31 12:37:18 -08002508 if (res.IsEq()) {
Austin Schuh36244a12019-09-21 17:52:38 -07002509 return {iter, MatchKind::kEq};
2510 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002511 // Note: in the non-key-compare-to case, we don't need to walk all the way
2512 // down the tree if the keys are equal, but determining equality would
2513 // require doing an extra comparison on each node on the way down, and we
2514 // will need to go all the way to the leaf node in the expected case.
Austin Schuh36244a12019-09-21 17:52:38 -07002515 if (iter.node->leaf()) {
2516 break;
2517 }
2518 iter.node = iter.node->child(iter.position);
2519 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002520 // Note: in the non-key-compare-to case, the key may actually be equivalent
2521 // here (and the MatchKind::kNe is ignored).
Austin Schuh36244a12019-09-21 17:52:38 -07002522 return {iter, MatchKind::kNe};
2523}
2524
2525template <typename P>
2526template <typename K>
Austin Schuhb4691e92020-12-31 12:37:18 -08002527auto btree<P>::internal_lower_bound(const K &key) const
2528 -> SearchResult<iterator, is_key_compare_to::value> {
2529 if (!params_type::template can_have_multiple_equivalent_keys<K>()) {
2530 SearchResult<iterator, is_key_compare_to::value> ret = internal_locate(key);
2531 ret.value = internal_last(ret.value);
2532 return ret;
2533 }
2534 iterator iter(const_cast<node_type *>(root()));
2535 SearchResult<int, is_key_compare_to::value> res;
2536 bool seen_eq = false;
Austin Schuh36244a12019-09-21 17:52:38 -07002537 for (;;) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002538 res = iter.node->lower_bound(key, key_comp());
2539 iter.position = res.value;
Austin Schuh36244a12019-09-21 17:52:38 -07002540 if (iter.node->leaf()) {
2541 break;
2542 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002543 seen_eq = seen_eq || res.IsEq();
Austin Schuh36244a12019-09-21 17:52:38 -07002544 iter.node = iter.node->child(iter.position);
2545 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002546 if (res.IsEq()) return {iter, MatchKind::kEq};
2547 return {internal_last(iter), seen_eq ? MatchKind::kEq : MatchKind::kNe};
Austin Schuh36244a12019-09-21 17:52:38 -07002548}
2549
2550template <typename P>
2551template <typename K>
2552auto btree<P>::internal_upper_bound(const K &key) const -> iterator {
Austin Schuhb4691e92020-12-31 12:37:18 -08002553 iterator iter(const_cast<node_type *>(root()));
Austin Schuh36244a12019-09-21 17:52:38 -07002554 for (;;) {
2555 iter.position = iter.node->upper_bound(key, key_comp());
2556 if (iter.node->leaf()) {
2557 break;
2558 }
2559 iter.node = iter.node->child(iter.position);
2560 }
2561 return internal_last(iter);
2562}
2563
2564template <typename P>
2565template <typename K>
2566auto btree<P>::internal_find(const K &key) const -> iterator {
Austin Schuhb4691e92020-12-31 12:37:18 -08002567 SearchResult<iterator, is_key_compare_to::value> res = internal_locate(key);
Austin Schuh36244a12019-09-21 17:52:38 -07002568 if (res.HasMatch()) {
2569 if (res.IsEq()) {
2570 return res.value;
2571 }
2572 } else {
2573 const iterator iter = internal_last(res.value);
2574 if (iter.node != nullptr && !compare_keys(key, iter.key())) {
2575 return iter;
2576 }
2577 }
2578 return {nullptr, 0};
2579}
2580
2581template <typename P>
Austin Schuhb4691e92020-12-31 12:37:18 -08002582int btree<P>::internal_verify(const node_type *node, const key_type *lo,
2583 const key_type *hi) const {
Austin Schuh36244a12019-09-21 17:52:38 -07002584 assert(node->count() > 0);
2585 assert(node->count() <= node->max_count());
2586 if (lo) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002587 assert(!compare_keys(node->key(node->start()), *lo));
Austin Schuh36244a12019-09-21 17:52:38 -07002588 }
2589 if (hi) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002590 assert(!compare_keys(*hi, node->key(node->finish() - 1)));
Austin Schuh36244a12019-09-21 17:52:38 -07002591 }
Austin Schuhb4691e92020-12-31 12:37:18 -08002592 for (int i = node->start() + 1; i < node->finish(); ++i) {
Austin Schuh36244a12019-09-21 17:52:38 -07002593 assert(!compare_keys(node->key(i), node->key(i - 1)));
2594 }
2595 int count = node->count();
2596 if (!node->leaf()) {
Austin Schuhb4691e92020-12-31 12:37:18 -08002597 for (int i = node->start(); i <= node->finish(); ++i) {
Austin Schuh36244a12019-09-21 17:52:38 -07002598 assert(node->child(i) != nullptr);
2599 assert(node->child(i)->parent() == node);
2600 assert(node->child(i)->position() == i);
Austin Schuhb4691e92020-12-31 12:37:18 -08002601 count += internal_verify(node->child(i),
2602 i == node->start() ? lo : &node->key(i - 1),
2603 i == node->finish() ? hi : &node->key(i));
Austin Schuh36244a12019-09-21 17:52:38 -07002604 }
2605 }
2606 return count;
2607}
2608
2609} // namespace container_internal
Austin Schuhb4691e92020-12-31 12:37:18 -08002610ABSL_NAMESPACE_END
Austin Schuh36244a12019-09-21 17:52:38 -07002611} // namespace absl
2612
2613#endif // ABSL_CONTAINER_INTERNAL_BTREE_H_