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