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