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