34#ifndef PHMAP_BTREE_BTREE_CONTAINER_H_
35#define PHMAP_BTREE_BTREE_CONTAINER_H_
40 #pragma warning(disable : 4127)
41 #pragma warning(disable : 4324)
42 #pragma warning(disable : 4355)
43 #pragma warning(disable : 4365)
44 #pragma warning(disable : 4514)
45 #pragma warning(disable : 4623)
46 #pragma warning(disable : 4625)
47 #pragma warning(disable : 4626)
48 #pragma warning(disable : 4710)
49 #pragma warning(disable : 4711)
50 #pragma warning(disable : 4820)
51 #pragma warning(disable : 4868)
52 #pragma warning(disable : 5026)
53 #pragma warning(disable : 5027)
54 #pragma warning(disable : 5045)
64#include "phmap_fwd_decl.h"
65#include "phmap_base.h"
67#if PHMAP_HAVE_STD_STRING_VIEW
68 #include <string_view>
73#if defined(_MSC_VER) && !defined(__clang__) && !defined(__GNUC__)
74 #define PHMAP_META_INTERNAL_STD_CONSTRUCTION_TRAITS_DONT_CHECK_DESTRUCTION 1
81 struct is_trivially_destructible;
87 namespace type_traits_internal {
90#if defined(_MSC_VER) && !defined(__GNUC__)
92 #pragma warning(disable : 4624)
101#if defined(_MSC_VER) && !defined(__GNUC__)
107 : std::integral_constant<
108 bool, std::is_move_constructible<
109 type_traits_internal::SingleMemberUnion<T>>::value &&
110 phmap::is_trivially_destructible<T>::value> {};
114 : std::integral_constant<
115 bool, std::is_copy_constructible<
116 type_traits_internal::SingleMemberUnion<T>>::value &&
117 phmap::is_trivially_destructible<T>::value> {};
133 template <
typename... Ts>
137 template <
typename T>
139 : std::integral_constant<
140 bool, !(std::is_reference<T>::value ||
141 std::is_const<typename std::add_const<T>::type>::value)> {};
144 namespace type_traits_internal {
146 template <
typename T>
148 using ExtentsRemoved =
typename std::remove_all_extents<T>::type;
149 static constexpr bool kIsCopyOrMoveConstructible =
150 std::is_copy_constructible<ExtentsRemoved>::value ||
151 std::is_move_constructible<ExtentsRemoved>::value;
152 static constexpr bool kIsCopyOrMoveAssignable =
157 static constexpr bool kValue =
158 (__has_trivial_copy(ExtentsRemoved) || !kIsCopyOrMoveConstructible) &&
159 (__has_trivial_assign(ExtentsRemoved) || !kIsCopyOrMoveAssignable) &&
160 (kIsCopyOrMoveConstructible || kIsCopyOrMoveAssignable) &&
164 !std::is_reference<ExtentsRemoved>::value;
167 template <
typename T>
169 : std::integral_constant<
170 bool, type_traits_internal::is_trivially_copyable_impl<T>::kValue> {};
173 namespace swap_internal {
183 using IsSwappableImpl =
decltype(swap(std::declval<T&>(), std::declval<T&>()));
187 class IsNoexcept = std::integral_constant<
188 bool,
noexcept(swap(std::declval<T&>(), std::declval<T&>()))>>
189 using IsNothrowSwappableImpl =
typename std::enable_if<IsNoexcept::value>::type;
199 template <class T, phmap::enable_if_t<IsSwappable<T>::value,
int> = 0>
204 using StdSwapIsUnconstrained = IsSwappable<void()>;
208 namespace type_traits_internal {
211 using swap_internal::IsNothrowSwappable;
212 using swap_internal::IsSwappable;
213 using swap_internal::Swap;
214 using swap_internal::StdSwapIsUnconstrained;
218 namespace compare_internal {
220 using value_type =
int8_t;
222 template <
typename T>
224 static_assert(
sizeof(T) < 0,
"Only literal `0` is allowed.");
227 template <
typename NullPtrT = std::
nullptr_t>
233 typename =
typename std::enable_if<
234 std::is_same<T, std::nullptr_t>::value ||
235 (std::is_integral<T>::value && !std::is_same<T, int>::value)>::type,
240 enum class eq : value_type {
244 nonequivalent = nonequal,
247 enum class ord : value_type { less = -1, greater = 1 };
249 enum class ncmp : value_type { unordered = -127 };
251#if defined(__cpp_inline_variables) && !defined(_MSC_VER)
253#define PHMAP_COMPARE_INLINE_BASECLASS_DECL(name)
255#define PHMAP_COMPARE_INLINE_SUBCLASS_DECL(type, name) \
256 static const type name;
258#define PHMAP_COMPARE_INLINE_INIT(type, name, init) \
259 inline constexpr type type::name(init)
263#define PHMAP_COMPARE_INLINE_BASECLASS_DECL(name) \
266#define PHMAP_COMPARE_INLINE_SUBCLASS_DECL(type, name)
268#define PHMAP_COMPARE_INLINE_INIT(type, name, init) \
269 template <typename T> \
270 const T compare_internal::type##_base<T>::name(init)
277 template <
typename T>
279 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equivalent)
280 PHMAP_COMPARE_INLINE_BASECLASS_DECL(nonequivalent)
283 template <
typename T>
285 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equal)
286 PHMAP_COMPARE_INLINE_BASECLASS_DECL(nonequal)
287 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equivalent)
288 PHMAP_COMPARE_INLINE_BASECLASS_DECL(nonequivalent)
291 template <
typename T>
293 PHMAP_COMPARE_INLINE_BASECLASS_DECL(less)
294 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equivalent)
295 PHMAP_COMPARE_INLINE_BASECLASS_DECL(greater)
296 PHMAP_COMPARE_INLINE_BASECLASS_DECL(unordered)
299 template <
typename T>
301 PHMAP_COMPARE_INLINE_BASECLASS_DECL(less)
302 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equivalent)
303 PHMAP_COMPARE_INLINE_BASECLASS_DECL(greater)
306 template <
typename T>
308 PHMAP_COMPARE_INLINE_BASECLASS_DECL(less)
309 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equal)
310 PHMAP_COMPARE_INLINE_BASECLASS_DECL(equivalent)
311 PHMAP_COMPARE_INLINE_BASECLASS_DECL(greater)
318 explicit constexpr weak_equality(compare_internal::eq v) noexcept
319 : value_(
static_cast<compare_internal::value_type
>(v)) {}
323 PHMAP_COMPARE_INLINE_SUBCLASS_DECL(
weak_equality, equivalent)
324 PHMAP_COMPARE_INLINE_SUBCLASS_DECL(
weak_equality, nonequivalent)
327 friend constexpr bool operator==(
329 return v.value_ == 0;
331 friend constexpr bool operator!=(
333 return v.value_ != 0;
337 return 0 == v.value_;
341 return 0 != v.value_;
345 compare_internal::value_type value_;
348 compare_internal::eq::equivalent);
350 compare_internal::eq::nonequivalent);
355 : value_(
static_cast<compare_internal::value_type
>(v)) {}
366 return value_ == 0 ? weak_equality::equivalent
367 : weak_equality::nonequivalent;
370 friend constexpr bool operator==(
372 return v.value_ == 0;
374 friend constexpr bool operator!=(
376 return v.value_ != 0;
380 return 0 == v.value_;
384 return 0 != v.value_;
388 compare_internal::value_type value_;
391 PHMAP_COMPARE_INLINE_INIT(
strong_equality, equal, compare_internal::eq::equal);
393 compare_internal::eq::nonequal);
395 compare_internal::eq::equivalent);
397 compare_internal::eq::nonequivalent);
402 : value_(
static_cast<compare_internal::value_type
>(v)) {}
404 : value_(
static_cast<compare_internal::value_type
>(v)) {}
406 : value_(
static_cast<compare_internal::value_type
>(v)) {}
409 constexpr bool is_ordered()
const noexcept {
411 compare_internal::value_type(compare_internal::ncmp::unordered);
422 return value_ == 0 ? weak_equality::equivalent
423 : weak_equality::nonequivalent;
426 friend constexpr bool operator==(
428 return v.is_ordered() && v.value_ == 0;
430 friend constexpr bool operator!=(
432 return !v.is_ordered() || v.value_ != 0;
434 friend constexpr bool operator<(
436 return v.is_ordered() && v.value_ < 0;
438 friend constexpr bool operator<=(
440 return v.is_ordered() && v.value_ <= 0;
442 friend constexpr bool operator>(
444 return v.is_ordered() && v.value_ > 0;
446 friend constexpr bool operator>=(
448 return v.is_ordered() && v.value_ >= 0;
452 return v.is_ordered() && 0 == v.value_;
456 return !v.is_ordered() || 0 != v.value_;
460 return v.is_ordered() && 0 < v.value_;
464 return v.is_ordered() && 0 <= v.value_;
468 return v.is_ordered() && 0 > v.value_;
472 return v.is_ordered() && 0 >= v.value_;
476 compare_internal::value_type value_;
479 PHMAP_COMPARE_INLINE_INIT(
partial_ordering, less, compare_internal::ord::less);
481 compare_internal::eq::equivalent);
483 compare_internal::ord::greater);
485 compare_internal::ncmp::unordered);
489 explicit constexpr weak_ordering(compare_internal::eq v) noexcept
490 : value_(
static_cast<compare_internal::value_type
>(v)) {}
491 explicit constexpr weak_ordering(compare_internal::ord v) noexcept
492 : value_(
static_cast<compare_internal::value_type
>(v)) {}
497 PHMAP_COMPARE_INLINE_SUBCLASS_DECL(
weak_ordering, equivalent)
502 return value_ == 0 ? weak_equality::equivalent
503 : weak_equality::nonequivalent;
506 return value_ == 0 ? partial_ordering::equivalent
507 : (value_ < 0 ? partial_ordering::less
508 : partial_ordering::greater);
511 friend constexpr bool operator==(
513 return v.value_ == 0;
515 friend constexpr bool operator!=(
517 return v.value_ != 0;
519 friend constexpr bool operator<(
523 friend constexpr bool operator<=(
525 return v.value_ <= 0;
527 friend constexpr bool operator>(
531 friend constexpr bool operator>=(
533 return v.value_ >= 0;
537 return 0 == v.value_;
541 return 0 != v.value_;
549 return 0 <= v.value_;
557 return 0 >= v.value_;
561 compare_internal::value_type value_;
564 PHMAP_COMPARE_INLINE_INIT(
weak_ordering, less, compare_internal::ord::less);
566 compare_internal::eq::equivalent);
568 compare_internal::ord::greater);
573 : value_(
static_cast<compare_internal::value_type
>(v)) {}
575 : value_(
static_cast<compare_internal::value_type
>(v)) {}
586 return value_ == 0 ? weak_equality::equivalent
587 : weak_equality::nonequivalent;
590 return value_ == 0 ? strong_equality::equal : strong_equality::nonequal;
593 return value_ == 0 ? partial_ordering::equivalent
594 : (value_ < 0 ? partial_ordering::less
595 : partial_ordering::greater);
599 ? weak_ordering::equivalent
600 : (value_ < 0 ? weak_ordering::less : weak_ordering::greater);
603 friend constexpr bool operator==(
605 return v.value_ == 0;
607 friend constexpr bool operator!=(
609 return v.value_ != 0;
611 friend constexpr bool operator<(
615 friend constexpr bool operator<=(
617 return v.value_ <= 0;
619 friend constexpr bool operator>(
623 friend constexpr bool operator>=(
625 return v.value_ >= 0;
629 return 0 == v.value_;
633 return 0 != v.value_;
641 return 0 <= v.value_;
649 return 0 >= v.value_;
653 compare_internal::value_type value_;
655 PHMAP_COMPARE_INLINE_INIT(
strong_ordering, less, compare_internal::ord::less);
656 PHMAP_COMPARE_INLINE_INIT(
strong_ordering, equal, compare_internal::eq::equal);
658 compare_internal::eq::equivalent);
660 compare_internal::ord::greater);
662#undef PHMAP_COMPARE_INLINE_BASECLASS_DECL
663#undef PHMAP_COMPARE_INLINE_SUBCLASS_DECL
664#undef PHMAP_COMPARE_INLINE_INIT
666 namespace compare_internal {
672 template <
typename BoolType,
673 phmap::enable_if_t<std::is_same<bool, BoolType>::value,
int> = 0>
674 constexpr bool compare_result_as_less_than(
const BoolType r) {
return r; }
679 template <
typename Compare,
typename K,
typename LK>
680 constexpr bool do_less_than_comparison(
const Compare &compare,
const K &x,
682 return compare_result_as_less_than(compare(x, y));
688 template <
typename Int,
689 phmap::enable_if_t<std::is_same<int, Int>::value,
int> = 0>
691 return c < 0 ? phmap::weak_ordering::less
692 : c == 0 ? phmap::weak_ordering::equivalent
693 : phmap::weak_ordering::greater;
701 typename Compare,
typename K,
typename LK,
702 phmap::enable_if_t<!std::is_same<bool, phmap::invoke_result_t<
703 Compare,
const K &,
const LK &>>::value,
706 const K &x,
const LK &y) {
707 return compare_result_as_ordering(compare(x, y));
710 typename Compare,
typename K,
typename LK,
711 phmap::enable_if_t<std::is_same<bool, phmap::invoke_result_t<Compare,
712 const K &,
const LK &>>::value,
715 const K &x,
const LK &y) {
716 return compare(x, y) ? phmap::weak_ordering::less
717 : compare(y, x) ? phmap::weak_ordering::greater
718 : phmap::weak_ordering::equivalent;
731 template <
typename Compare,
typename T>
732 using btree_is_key_compare_to =
733 std::is_convertible<phmap::invoke_result_t<Compare, const T &, const T &>,
736 struct StringBtreeDefaultLess {
737 using is_transparent = void;
739 StringBtreeDefaultLess() =
default;
742 StringBtreeDefaultLess(std::less<std::string>) {}
743#if PHMAP_HAVE_STD_STRING_VIEW
744 StringBtreeDefaultLess(std::less<std::string_view>) {}
748 std::string_view rhs)
const {
749 return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
753 std::string rhs)
const {
754 return compare_internal::compare_result_as_ordering(lhs.compare(rhs));
759 struct StringBtreeDefaultGreater {
760 using is_transparent = void;
762 StringBtreeDefaultGreater() =
default;
764 StringBtreeDefaultGreater(std::greater<std::string>) {}
765#if PHMAP_HAVE_STD_STRING_VIEW
766 StringBtreeDefaultGreater(std::greater<std::string_view>) {}
769 std::string_view rhs)
const {
770 return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
774 std::string rhs)
const {
775 return compare_internal::compare_result_as_ordering(rhs.compare(lhs));
791 template <
typename Compare>
792 struct key_compare_to_adapter {
793 using type = Compare;
797 struct key_compare_to_adapter<std::less<std::string>> {
798 using type = StringBtreeDefaultLess;
802 struct key_compare_to_adapter<phmap::Less<std::string>> {
803 using type = StringBtreeDefaultLess;
807 struct key_compare_to_adapter<std::greater<std::string>> {
808 using type = StringBtreeDefaultGreater;
811#if PHMAP_HAVE_STD_STRING_VIEW
813 struct key_compare_to_adapter<std::less<std::string_view>> {
814 using type = StringBtreeDefaultLess;
818 struct key_compare_to_adapter<phmap::Less<std::string_view>> {
819 using type = StringBtreeDefaultLess;
823 struct key_compare_to_adapter<std::greater<std::string_view>> {
824 using type = StringBtreeDefaultGreater;
828 template <
typename Key,
typename Compare,
typename Alloc,
int TargetNodeSize,
829 bool Multi,
typename SlotPolicy>
830 struct common_params {
833 using key_compare =
typename key_compare_to_adapter<Compare>::type;
836 using is_key_compare_to = btree_is_key_compare_to<key_compare, Key>;
838 using allocator_type = Alloc;
839 using key_type = Key;
840 using size_type = std::make_signed<size_t>::type;
841 using difference_type = ptrdiff_t;
844 using is_multi_container = std::integral_constant<bool, Multi>;
846 using slot_policy = SlotPolicy;
847 using slot_type =
typename slot_policy::slot_type;
848 using value_type =
typename slot_policy::value_type;
849 using init_type =
typename slot_policy::mutable_value_type;
850 using pointer = value_type *;
851 using const_pointer =
const value_type *;
852 using reference = value_type &;
853 using const_reference =
const value_type &;
856 kTargetNodeSize = TargetNodeSize,
862 TargetNodeSize - (
sizeof(
void *) + 4),
867 using node_count_type =
868 phmap::conditional_t<(kNodeValueSpace /
sizeof(value_type) >
869 (std::numeric_limits<uint8_t>::max)()),
874 static value_type &element(slot_type *slot) {
875 return slot_policy::element(slot);
877 static const value_type &element(
const slot_type *slot) {
878 return slot_policy::element(slot);
880 template <
class... Args>
881 static void construct(Alloc *alloc, slot_type *slot, Args &&... args) {
882 slot_policy::construct(alloc, slot, std::forward<Args>(args)...);
884 static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
885 slot_policy::construct(alloc, slot, other);
887 static void destroy(Alloc *alloc, slot_type *slot) {
888 slot_policy::destroy(alloc, slot);
890 static void transfer(Alloc *alloc, slot_type *new_slot, slot_type *old_slot) {
891 construct(alloc, new_slot, old_slot);
892 destroy(alloc, old_slot);
894 static void swap(Alloc *alloc, slot_type *a, slot_type *b) {
895 slot_policy::swap(alloc, a, b);
897 static void move(Alloc *alloc, slot_type *src, slot_type *dest) {
898 slot_policy::move(alloc, src, dest);
900 static void move(Alloc *alloc, slot_type *first, slot_type *last,
902 slot_policy::move(alloc, first, last, result);
908 template <
typename Key,
typename Data,
typename Compare,
typename Alloc,
909 int TargetNodeSize,
bool Multi>
910 struct map_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
911 phmap::priv::map_slot_policy<Key, Data>> {
912 using super_type =
typename map_params::common_params;
913 using mapped_type = Data;
916 using slot_policy =
typename super_type::slot_policy;
917 using slot_type =
typename super_type::slot_type;
918 using value_type =
typename super_type::value_type;
919 using init_type =
typename super_type::init_type;
921 using key_compare =
typename super_type::key_compare;
925 explicit value_compare(
const key_compare &cmp) : key_compare(cmp) {}
927 template <
typename T,
typename U>
928 auto operator()(
const T &left,
const U &right)
const
929 ->
decltype(std::declval<key_compare>()(left.first, right.first)) {
930 return key_compare::operator()(left.first, right.first);
933 using is_map_container = std::true_type;
935 static const Key &key(
const value_type &x) {
return x.first; }
936 static const Key &key(
const init_type &x) {
return x.first; }
937 static const Key &key(
const slot_type *x) {
return slot_policy::key(x); }
938 static mapped_type &value(value_type *value) {
return value->second; }
943 template <
typename Key>
944 struct set_slot_policy {
945 using slot_type = Key;
946 using value_type = Key;
947 using mutable_value_type = Key;
949 static value_type &element(slot_type *slot) {
return *slot; }
950 static const value_type &element(
const slot_type *slot) {
return *slot; }
952 template <
typename Alloc,
class... Args>
953 static void construct(Alloc *alloc, slot_type *slot, Args &&... args) {
955 std::forward<Args>(args)...);
958 template <
typename Alloc>
959 static void construct(Alloc *alloc, slot_type *slot, slot_type *other) {
963 template <
typename Alloc>
964 static void destroy(Alloc *alloc, slot_type *slot) {
968 template <
typename Alloc>
969 static void swap(Alloc * , slot_type *a, slot_type *b) {
974 template <
typename Alloc>
975 static void move(Alloc * , slot_type *src, slot_type *dest) {
976 *dest = std::move(*src);
979 template <
typename Alloc>
980 static void move(Alloc *alloc, slot_type *first, slot_type *last,
982 for (slot_type *src = first, *dest = result; src != last; ++src, ++dest)
983 move(alloc, src, dest);
989 template <
typename Key,
typename Compare,
typename Alloc,
int TargetNodeSize,
991 struct set_params : common_params<Key, Compare, Alloc, TargetNodeSize, Multi,
992 set_slot_policy<Key>> {
993 using value_type = Key;
994 using slot_type =
typename set_params::common_params::slot_type;
995 using value_compare =
typename set_params::common_params::key_compare;
996 using is_map_container = std::false_type;
998 static const Key &key(
const value_type &x) {
return x; }
999 static const Key &key(
const slot_type *x) {
return *x; }
1006 template <
typename Compare>
1007 struct upper_bound_adapter {
1008 explicit upper_bound_adapter(
const Compare &c) : comp(c) {}
1009 template <
typename K,
typename LK>
1010 bool operator()(
const K &a,
const LK &b)
const {
1012 return !phmap::compare_internal::compare_result_as_less_than(comp(b, a));
1019 enum class MatchKind :
uint8_t { kEq, kNe };
1021 template <
typename V,
bool IsCompareTo>
1022 struct SearchResult {
1026 static constexpr bool HasMatch() {
return true; }
1027 bool IsEq()
const {
return match == MatchKind::kEq; }
1033 template <
typename V>
1034 struct SearchResult<V, false> {
1037 static constexpr bool HasMatch() {
return false; }
1038 static constexpr bool IsEq() {
return false; }
1044 template <
typename Params>
1046 using is_key_compare_to =
typename Params::is_key_compare_to;
1047 using is_multi_container =
typename Params::is_multi_container;
1048 using field_type =
typename Params::node_count_type;
1049 using allocator_type =
typename Params::allocator_type;
1050 using slot_type =
typename Params::slot_type;
1053 using params_type = Params;
1054 using key_type =
typename Params::key_type;
1055 using value_type =
typename Params::value_type;
1056 using pointer =
typename Params::pointer;
1057 using const_pointer =
typename Params::const_pointer;
1058 using reference =
typename Params::reference;
1059 using const_reference =
typename Params::const_reference;
1060 using key_compare =
typename Params::key_compare;
1061 using size_type =
typename Params::size_type;
1062 using difference_type =
typename Params::difference_type;
1069 using use_linear_search = std::integral_constant<
1071 std::is_arithmetic<key_type>::value &&
1072 (std::is_same<phmap::Less<key_type>, key_compare>::value ||
1073 std::is_same<std::less<key_type>, key_compare>::value ||
1074 std::is_same<std::greater<key_type>, key_compare>::value)>;
1077 ~btree_node() =
default;
1078 btree_node(btree_node
const &) =
delete;
1079 btree_node &operator=(btree_node
const &) =
delete;
1082 constexpr static size_type Alignment() {
1083 static_assert(LeafLayout(1).Alignment() == InternalLayout().Alignment(),
1084 "Alignment of all nodes must be equal.");
1085 return (size_type)InternalLayout().Alignment();
1089 btree_node() =
default;
1092 using layout_type = phmap::priv::Layout<btree_node *, field_type,
1093 slot_type, btree_node *>;
1094 constexpr static size_type SizeWithNValues(size_type n) {
1095 return (size_type)layout_type( 1,
1102 constexpr static size_type MinimumOverhead() {
1103 return (size_type)(SizeWithNValues(1) -
sizeof(value_type));
1108 constexpr static size_type NodeTargetValues(
const int begin,
const int end) {
1109 return begin == end ? begin
1110 : SizeWithNValues((begin + end) / 2 + 1) >
1111 params_type::kTargetNodeSize
1112 ? NodeTargetValues(begin, (begin + end) / 2)
1113 : NodeTargetValues((begin + end) / 2 + 1, end);
1117 kTargetNodeSize = params_type::kTargetNodeSize,
1118 kNodeTargetValues = NodeTargetValues(0, params_type::kTargetNodeSize),
1123 kNodeValues = kNodeTargetValues >= 3 ? kNodeTargetValues : 3,
1127 kInternalNodeMaxCount = 0,
1131 constexpr static layout_type LeafLayout(
const int max_values = kNodeValues) {
1132 return layout_type( 1,
1137 constexpr static layout_type InternalLayout() {
1138 return layout_type( 1,
1143 constexpr static size_type LeafSize(
const int max_values = kNodeValues) {
1144 return (size_type)LeafLayout(max_values).AllocSize();
1146 constexpr static size_type InternalSize() {
1147 return (size_type)InternalLayout().AllocSize();
1152 template <
size_type N>
1153 inline typename layout_type::template ElementType<N> *GetField() {
1155 assert(N < 3 || !leaf());
1156 return InternalLayout().template Pointer<N>(
reinterpret_cast<char *
>(
this));
1159 template <
size_type N>
1160 inline const typename layout_type::template ElementType<N> *GetField()
const {
1161 assert(N < 3 || !leaf());
1162 return InternalLayout().template Pointer<N>(
1163 reinterpret_cast<const char *
>(
this));
1166 void set_parent(btree_node *p) { *GetField<0>() = p; }
1167 field_type &mutable_count() {
return GetField<1>()[2]; }
1168 slot_type *slot(size_type i) {
return &GetField<2>()[i]; }
1169 const slot_type *slot(size_type i)
const {
return &GetField<2>()[i]; }
1170 void set_position(field_type v) { GetField<1>()[0] = v; }
1171 void set_start(field_type v) { GetField<1>()[1] = v; }
1172 void set_count(field_type v) { GetField<1>()[2] = v; }
1173 void set_max_count(field_type v) { GetField<1>()[3] = v; }
1178 bool leaf()
const {
return GetField<1>()[3] != kInternalNodeMaxCount; }
1181 field_type position()
const {
return GetField<1>()[0]; }
1184 field_type start()
const {
return GetField<1>()[1]; }
1187 field_type count()
const {
return GetField<1>()[2]; }
1188 field_type max_count()
const {
1191 const field_type max_cnt = GetField<1>()[3];
1192 return max_cnt == field_type{kInternalNodeMaxCount}
1193 ? field_type{kNodeValues}
1198 btree_node *parent()
const {
return *GetField<0>(); }
1202 bool is_root()
const {
return parent()->leaf(); }
1204 assert(parent()->is_root());
1205 set_parent(parent()->parent());
1209 const key_type &key(size_type i)
const {
return params_type::key(slot(i)); }
1210 reference value(size_type i) {
return params_type::element(slot(i)); }
1211 const_reference value(size_type i)
const {
return params_type::element(slot(i)); }
1214 btree_node *child(size_type i)
const {
return GetField<3>()[i]; }
1215 btree_node *&mutable_child(size_type i) {
return GetField<3>()[i]; }
1216 void clear_child(size_type i) {
1217 phmap::priv::SanitizerPoisonObject(&mutable_child(i));
1219 void set_child(size_type i, btree_node *c) {
1220 phmap::priv::SanitizerUnpoisonObject(&mutable_child(i));
1221 mutable_child(i) = c;
1222 c->set_position((field_type)i);
1224 void init_child(
int i, btree_node *c) {
1226 c->set_parent(
this);
1230 template <
typename K>
1231 SearchResult<int, is_key_compare_to::value> lower_bound(
1232 const K &k,
const key_compare &comp)
const {
1233 return use_linear_search::value ? linear_search(k, comp)
1234 : binary_search(k, comp);
1237 template <
typename K>
1238 int upper_bound(
const K &k,
const key_compare &comp)
const {
1239 auto upper_compare = upper_bound_adapter<key_compare>(comp);
1240 return use_linear_search::value ? linear_search(k, upper_compare).value
1241 : binary_search(k, upper_compare).value;
1244 template <
typename K,
typename Compare>
1245 SearchResult<int, btree_is_key_compare_to<Compare, key_type>::value>
1246 linear_search(
const K &k,
const Compare &comp)
const {
1247 return linear_search_impl(k, 0, count(), comp,
1248 btree_is_key_compare_to<Compare, key_type>());
1251 template <
typename K,
typename Compare>
1252 SearchResult<int, btree_is_key_compare_to<Compare, key_type>::value>
1253 binary_search(
const K &k,
const Compare &comp)
const {
1254 return binary_search_impl(k, 0, count(), comp,
1255 btree_is_key_compare_to<Compare, key_type>());
1260 template <
typename K,
typename Compare>
1261 SearchResult<int, false> linear_search_impl(
1262 const K &k,
int s,
const int e,
const Compare &comp,
1263 std::false_type )
const {
1265 if (!comp(key(s), k)) {
1275 template <
typename K,
typename Compare>
1276 SearchResult<int, true> linear_search_impl(
1277 const K &k,
int s,
const int e,
const Compare &comp,
1278 std::true_type )
const {
1282 return {s, MatchKind::kEq};
1288 return {s, MatchKind::kNe};
1293 template <
typename K,
typename Compare>
1294 SearchResult<int, false> binary_search_impl(
1295 const K &k,
int s,
int e,
const Compare &comp,
1296 std::false_type )
const {
1298 const int mid = (s + e) >> 1;
1299 if (comp(key(mid), k)) {
1310 template <
typename K,
typename CompareTo>
1311 SearchResult<int, true> binary_search_impl(
1312 const K &k,
int s,
int e,
const CompareTo &comp,
1313 std::true_type )
const {
1314 if (is_multi_container::value) {
1315 MatchKind exact_match = MatchKind::kNe;
1317 const int mid = (s + e) >> 1;
1327 exact_match = MatchKind::kEq;
1331 return {s, exact_match};
1334 const int mid = (s + e) >> 1;
1341 return {mid, MatchKind::kEq};
1344 return {s, MatchKind::kNe};
1350 template <
typename... Args>
1351 void emplace_value(size_type i, allocator_type *alloc, Args &&... args);
1355 void remove_value(
int i, allocator_type *alloc);
1359 void remove_values_ignore_children(
int i, size_type to_erase,
1360 allocator_type *alloc);
1363 void rebalance_right_to_left(
int to_move, btree_node *right,
1364 allocator_type *alloc);
1365 void rebalance_left_to_right(
int to_move, btree_node *right,
1366 allocator_type *alloc);
1369 void split(
int insert_position, btree_node *dest, allocator_type *alloc);
1373 void merge(btree_node *sibling, allocator_type *alloc);
1376 void swap(btree_node *src, allocator_type *alloc);
1379 static btree_node *init_leaf(btree_node *n, btree_node *parent,
1381 n->set_parent(parent);
1385 n->set_max_count((field_type)max_cnt);
1386 phmap::priv::SanitizerPoisonMemoryRegion(
1387 n->slot(0), max_cnt *
sizeof(slot_type));
1390 static btree_node *init_internal(btree_node *n, btree_node *parent) {
1391 init_leaf(n, parent, kNodeValues);
1394 n->set_max_count(kInternalNodeMaxCount);
1395 phmap::priv::SanitizerPoisonMemoryRegion(
1396 &n->mutable_child(0), (kNodeValues + 1) *
sizeof(btree_node *));
1399 void destroy(allocator_type *alloc) {
1400 for (
int i = 0; i < count(); ++i) {
1401 value_destroy(i, alloc);
1407 static bool testonly_uses_linear_node_search() {
1408 return use_linear_search::value;
1412 template <
typename... Args>
1413 void value_init(
const size_type i, allocator_type *alloc, Args &&... args) {
1414 phmap::priv::SanitizerUnpoisonObject(slot(i));
1415 params_type::construct(alloc, slot(i), std::forward<Args>(args)...);
1417 void value_destroy(
const size_type i, allocator_type *alloc) {
1418 params_type::destroy(alloc, slot(i));
1419 phmap::priv::SanitizerPoisonObject(slot(i));
1424 void uninitialized_move_n(
const size_type n,
const size_type i,
1425 const size_type j, btree_node *x,
1426 allocator_type *alloc) {
1427 phmap::priv::SanitizerUnpoisonMemoryRegion(
1428 x->slot(j), n *
sizeof(slot_type));
1429 for (slot_type *src = slot(i), *end = src + n, *dest = x->slot(j);
1430 src != end; ++src, ++dest) {
1431 params_type::construct(alloc, dest, src);
1436 void value_destroy_n(
const size_type i,
const size_type n,
1437 allocator_type *alloc) {
1438 for (
int j = 0; j < n; ++j) {
1439 value_destroy(i + j, alloc);
1443 template <
typename P>
1445 template <
typename N,
typename R,
typename P>
1446 friend struct btree_iterator;
1447 friend class BtreeNodePeer;
1450 template <
typename Node,
typename Reference,
typename Po
inter>
1451 struct btree_iterator {
1453 using key_type =
typename Node::key_type;
1454 using size_type =
typename Node::size_type;
1455 using params_type =
typename Node::params_type;
1457 using node_type = Node;
1458 using normal_node =
typename std::remove_const<Node>::type;
1459 using const_node =
const Node;
1460 using normal_pointer =
typename params_type::pointer;
1461 using normal_reference =
typename params_type::reference;
1462 using const_pointer =
typename params_type::const_pointer;
1463 using const_reference =
typename params_type::const_reference;
1464 using slot_type =
typename params_type::slot_type;
1467 btree_iterator<normal_node, normal_reference, normal_pointer>;
1468 using const_iterator =
1469 btree_iterator<const_node, const_reference, const_pointer>;
1473 using difference_type =
typename Node::difference_type;
1474 using value_type =
typename params_type::value_type;
1475 using pointer = Pointer;
1476 using reference = Reference;
1477 using iterator_category = std::bidirectional_iterator_tag;
1479 btree_iterator() : node(nullptr), position(-1) {}
1480 btree_iterator(Node *n,
int p) : node(n), position(p) {}
1486 template <
typename N,
typename R,
typename P,
1488 std::is_same<btree_iterator<N, R, P>, iterator>::value &&
1489 std::is_same<btree_iterator, const_iterator>::value,
1491 btree_iterator(
const btree_iterator<N, R, P> &x)
1492 : node(x.node), position(x.position) {}
1499 template <
typename N,
typename R,
typename P,
1501 std::is_same<btree_iterator<N, R, P>, const_iterator>::value &&
1502 std::is_same<btree_iterator, iterator>::value,
1504 explicit btree_iterator(
const btree_iterator<N, R, P> &x)
1505 : node(const_cast<node_type *>(x.node)), position(x.position) {}
1509 if (node->leaf() && ++position < node->count()) {
1514 void increment_slow();
1517 if (node->leaf() && --position >= 0) {
1522 void decrement_slow();
1525 bool operator==(
const const_iterator &x)
const {
1526 return node == x.node && position == x.position;
1528 bool operator!=(
const const_iterator &x)
const {
1529 return node != x.node || position != x.position;
1533 reference operator*()
const {
1534 return node->value(position);
1536 pointer operator->()
const {
1537 return &node->value(position);
1540 btree_iterator& operator++() {
1544 btree_iterator& operator--() {
1548 btree_iterator operator++(
int) {
1549 btree_iterator tmp = *
this;
1553 btree_iterator operator--(
int) {
1554 btree_iterator tmp = *
this;
1560 template <
typename Params>
1562 template <
typename Tree>
1563 friend class btree_container;
1564 template <
typename Tree>
1565 friend class btree_set_container;
1566 template <
typename Tree>
1567 friend class btree_map_container;
1568 template <
typename Tree>
1569 friend class btree_multiset_container;
1570 template <
typename N,
typename R,
typename P>
1571 friend struct btree_iterator;
1572 template <
typename TreeType,
typename CheckerType>
1573 friend class base_checker;
1575 const key_type &key()
const {
return node->key(position); }
1576 slot_type *slot() {
return node->slot(position); }
1585 template <
typename Params>
1587 using node_type = btree_node<Params>;
1588 using is_key_compare_to =
typename Params::is_key_compare_to;
1592 struct alignas(node_type::Alignment()) EmptyNodeType : node_type {
1593 using field_type =
typename node_type::field_type;
1595 field_type position = 0;
1596 field_type start = 0;
1597 field_type count = 0;
1600 field_type max_count = node_type::kInternalNodeMaxCount + 1;
1604 EmptyNodeType() : parent(this) {}
1606 constexpr EmptyNodeType(node_type *p) : parent(p) {}
1610 static node_type *EmptyNode() {
1612 static EmptyNodeType* empty_node =
new EmptyNodeType;
1614 assert(empty_node->parent == empty_node);
1617 static constexpr EmptyNodeType empty_node(
1618 const_cast<EmptyNodeType *
>(&empty_node));
1619 return const_cast<EmptyNodeType *
>(&empty_node);
1624 kNodeValues = node_type::kNodeValues,
1625 kMinNodeValues = kNodeValues / 2,
1629 using size_type =
typename Params::size_type;
1631 node_stats(size_type l, size_type i)
1636 node_stats& operator+=(
const node_stats &x) {
1637 leaf_nodes += x.leaf_nodes;
1638 internal_nodes += x.internal_nodes;
1642 size_type leaf_nodes;
1643 size_type internal_nodes;
1647 using key_type =
typename Params::key_type;
1648 using value_type =
typename Params::value_type;
1649 using size_type =
typename Params::size_type;
1650 using difference_type =
typename Params::difference_type;
1651 using key_compare =
typename Params::key_compare;
1652 using value_compare =
typename Params::value_compare;
1653 using allocator_type =
typename Params::allocator_type;
1654 using reference =
typename Params::reference;
1655 using const_reference =
typename Params::const_reference;
1656 using pointer =
typename Params::pointer;
1657 using const_pointer =
typename Params::const_pointer;
1658 using iterator = btree_iterator<node_type, reference, pointer>;
1659 using const_iterator =
typename iterator::const_iterator;
1660 using reverse_iterator = std::reverse_iterator<iterator>;
1661 using const_reverse_iterator = std::reverse_iterator<const_iterator>;
1662 using node_handle_type = node_handle<Params, Params, allocator_type>;
1665 using params_type = Params;
1666 using slot_type =
typename Params::slot_type;
1670 const value_type &maybe_move_from_iterator(const_iterator x) {
return *x; }
1671 value_type &&maybe_move_from_iterator(iterator x) {
return std::move(*x); }
1677 template <
typename Btree>
1678 void copy_or_move_values_in_order(Btree *x);
1681 constexpr static bool static_assert_validation();
1684 btree(
const key_compare &comp,
const allocator_type &alloc);
1686 btree(
const btree &x);
1687 btree(btree &&x) noexcept
1688 : root_(std::move(x.root_)),
1689 rightmost_(phmap::exchange(x.rightmost_, EmptyNode())),
1690 size_(phmap::exchange(x.size_, 0)) {
1691 x.mutable_root() = EmptyNode();
1697 static_assert(static_assert_validation(),
"This call must be elided.");
1702 btree &operator=(
const btree &x);
1703 btree &operator=(btree &&x)
noexcept;
1706 return iterator(leftmost(), 0);
1708 const_iterator begin()
const {
1709 return const_iterator(leftmost(), 0);
1711 iterator end() {
return iterator(rightmost_, rightmost_->count()); }
1712 const_iterator end()
const {
1713 return const_iterator(rightmost_, rightmost_->count());
1715 reverse_iterator rbegin() {
1716 return reverse_iterator(end());
1718 const_reverse_iterator rbegin()
const {
1719 return const_reverse_iterator(end());
1721 reverse_iterator rend() {
1722 return reverse_iterator(begin());
1724 const_reverse_iterator rend()
const {
1725 return const_reverse_iterator(begin());
1729 template <
typename K>
1730 iterator lower_bound(
const K &key) {
1731 return internal_end(internal_lower_bound(key));
1733 template <
typename K>
1734 const_iterator lower_bound(
const K &key)
const {
1735 return internal_end(internal_lower_bound(key));
1739 template <
typename K>
1740 iterator upper_bound(
const K &key) {
1741 return internal_end(internal_upper_bound(key));
1743 template <
typename K>
1744 const_iterator upper_bound(
const K &key)
const {
1745 return internal_end(internal_upper_bound(key));
1751 template <
typename K>
1752 std::pair<iterator, iterator> equal_range(
const K &key) {
1753 return {lower_bound(key), upper_bound(key)};
1755 template <
typename K>
1756 std::pair<const_iterator, const_iterator> equal_range(
const K &key)
const {
1757 return {lower_bound(key), upper_bound(key)};
1764 template <
typename... Args>
1765 std::pair<iterator, bool> insert_unique(
const key_type &key, Args &&... args);
1773 template <
typename... Args>
1774 std::pair<iterator, bool> insert_hint_unique(iterator position,
1775 const key_type &key,
1779 template <
typename InputIterator>
1780 void insert_iterator_unique(InputIterator b, InputIterator e);
1783 template <
typename ValueType>
1784 iterator insert_multi(
const key_type &key, ValueType &&v);
1787 template <
typename ValueType>
1788 iterator insert_multi(ValueType &&v) {
1789 return insert_multi(params_type::key(v), std::forward<ValueType>(v));
1796 template <
typename ValueType>
1797 iterator insert_hint_multi(iterator position, ValueType &&v);
1800 template <
typename InputIterator>
1801 void insert_iterator_multi(InputIterator b, InputIterator e);
1807 iterator erase(iterator iter);
1811 std::pair<size_type, iterator> erase(iterator begin, iterator end);
1815 template <
typename K>
1816 size_type erase_unique(
const K &key);
1820 template <
typename K>
1821 size_type erase_multi(
const K &key);
1825 template <
typename K>
1826 iterator find(
const K &key) {
1827 return internal_end(internal_find(key));
1829 template <
typename K>
1830 const_iterator find(
const K &key)
const {
1831 return internal_end(internal_find(key));
1835 template <
typename K>
1836 size_type count_unique(
const K &key)
const {
1837 const iterator beg = internal_find(key);
1838 if (beg.node ==
nullptr) {
1845 template <
typename K>
1846 size_type count_multi(
const K &key)
const {
1847 const auto range = equal_range(key);
1848 return std::distance(range.first, range.second);
1855 void swap(btree &x);
1857 const key_compare &key_comp() const noexcept {
1858 return root_.template get<0>();
1860 template <
typename K,
typename LK>
1861 bool compare_keys(
const K &x,
const LK &y)
const {
1862 return compare_internal::compare_result_as_less_than(key_comp()(x, y));
1865 value_compare value_comp()
const {
return value_compare(key_comp()); }
1868 void verify()
const;
1871 size_type size()
const {
return size_; }
1872 size_type max_size()
const {
return (std::numeric_limits<size_type>::max)(); }
1873 bool empty()
const {
return size_ == 0; }
1876 size_type height()
const {
1883 const node_type *n = root();
1887 }
while (n != root());
1893 size_type leaf_nodes()
const {
1894 return internal_stats(root()).leaf_nodes;
1896 size_type internal_nodes()
const {
1897 return internal_stats(root()).internal_nodes;
1899 size_type nodes()
const {
1900 node_stats stats = internal_stats(root());
1901 return stats.leaf_nodes + stats.internal_nodes;
1905 size_type bytes_used()
const {
1906 node_stats stats = internal_stats(root());
1907 if (stats.leaf_nodes == 1 && stats.internal_nodes == 0) {
1908 return sizeof(*this) +
1909 node_type::LeafSize(root()->max_count());
1911 return sizeof(*this) +
1912 stats.leaf_nodes * node_type::LeafSize() +
1913 stats.internal_nodes * node_type::InternalSize();
1918 static double average_bytes_per_value() {
1922 return node_type::LeafSize() / (kNodeValues * 0.75);
1930 double fullness()
const {
1931 if (empty())
return 0.0;
1932 return static_cast<double>(size()) / (nodes() * kNodeValues);
1938 double overhead()
const {
1939 if (empty())
return 0.0;
1940 return (bytes_used() - size() *
sizeof(value_type)) /
1941 static_cast<double>(size());
1945 allocator_type get_allocator()
const {
1951 node_type *root() {
return root_.template get<2>(); }
1952 const node_type *root()
const {
return root_.template get<2>(); }
1953 node_type *&mutable_root() noexcept {
return root_.template get<2>(); }
1954 key_compare *mutable_key_comp() noexcept {
return &root_.template get<0>(); }
1957 node_type *leftmost() {
return root()->parent(); }
1958 const node_type *leftmost()
const {
return root()->parent(); }
1961 allocator_type *mutable_allocator() noexcept {
1962 return &root_.template get<1>();
1964 const allocator_type &allocator() const noexcept {
1965 return root_.template get<1>();
1970 node_type *allocate(
const size_type sz) {
1971 return reinterpret_cast<node_type *
>(
1972 phmap::priv::Allocate<node_type::Alignment()>(
1973 mutable_allocator(), (
size_t)sz));
1977 node_type* new_internal_node(node_type *parent) {
1978 node_type *p = allocate(node_type::InternalSize());
1979 return node_type::init_internal(p, parent);
1981 node_type* new_leaf_node(node_type *parent) {
1982 node_type *p = allocate(node_type::LeafSize());
1983 return node_type::init_leaf(p, parent, kNodeValues);
1985 node_type *new_leaf_root_node(
const int max_count) {
1986 node_type *p = allocate(node_type::LeafSize(max_count));
1987 return node_type::init_leaf(p, p, max_count);
1991 void erase_same_node(iterator begin, iterator end);
1992 iterator erase_from_leaf_node(iterator begin, size_type to_erase);
1993 iterator rebalance_after_delete(iterator iter);
1996 void deallocate(
const size_type sz, node_type *node) {
1997 phmap::priv::Deallocate<node_type::Alignment()>(
1998 mutable_allocator(), node, (
size_t)sz);
2001 void delete_internal_node(node_type *node) {
2002 node->destroy(mutable_allocator());
2003 deallocate(node_type::InternalSize(), node);
2005 void delete_leaf_node(node_type *node) {
2006 node->destroy(mutable_allocator());
2007 deallocate(node_type::LeafSize(node->max_count()), node);
2011 void rebalance_or_split(iterator *iter);
2015 void merge_nodes(node_type *left, node_type *right);
2021 bool try_merge_or_rebalance(iterator *iter);
2026 iterator internal_end(iterator iter) {
2027 return iter.node !=
nullptr ? iter : end();
2029 const_iterator internal_end(const_iterator iter)
const {
2030 return iter.node !=
nullptr ? iter : end();
2035 template <
typename... Args>
2036 iterator internal_emplace(iterator iter, Args &&... args);
2043 template <
typename IterType>
2044 static IterType internal_last(IterType iter);
2054 template <
typename K>
2055 SearchResult<iterator, is_key_compare_to::value> internal_locate(
2056 const K &key)
const;
2058 template <
typename K>
2059 SearchResult<iterator, false> internal_locate_impl(
2060 const K &key, std::false_type )
const;
2062 template <
typename K>
2063 SearchResult<iterator, true> internal_locate_impl(
2064 const K &key, std::true_type )
const;
2067 template <
typename K>
2068 iterator internal_lower_bound(
const K &key)
const;
2071 template <
typename K>
2072 iterator internal_upper_bound(
const K &key)
const;
2075 template <
typename K>
2076 iterator internal_find(
const K &key)
const;
2079 void internal_clear(node_type *node);
2082 int internal_verify(
const node_type *node,
2083 const key_type *lo,
const key_type *hi)
const;
2085 node_stats internal_stats(
const node_type *node)
const {
2087 if (node ==
nullptr || (node == root() && empty())) {
2088 return node_stats(0, 0);
2091 return node_stats(1, 0);
2093 node_stats res(0, 1);
2094 for (
int i = 0; i <= node->count(); ++i) {
2095 res += internal_stats(node->child(i));
2102 static bool testonly_uses_linear_node_search() {
2103 return node_type::testonly_uses_linear_node_search();
2115 node_type *rightmost_;
2123 template <
typename P>
2124 template <
typename... Args>
2125 inline void btree_node<P>::emplace_value(
const size_type i,
2126 allocator_type *alloc,
2128 assert(i <= count());
2132 value_init(count(), alloc, slot(count() - 1));
2133 for (size_type j = count() - 1; j > i; --j)
2134 params_type::move(alloc, slot(j - 1), slot(j));
2135 value_destroy(i, alloc);
2137 value_init(i, alloc, std::forward<Args>(args)...);
2138 set_count((field_type)(count() + 1));
2140 if (!leaf() && count() > i + 1) {
2141 for (
int j = count(); j > i + 1; --j) {
2142 set_child(j, child(j - 1));
2148 template <
typename P>
2149 inline void btree_node<P>::remove_value(
const int i, allocator_type *alloc) {
2150 if (!leaf() && count() > i + 1) {
2151 assert(child(i + 1)->count() == 0);
2152 for (size_type j = i + 1; j < count(); ++j) {
2153 set_child(j, child(j + 1));
2155 clear_child(count());
2158 remove_values_ignore_children(i, 1, alloc);
2161 template <
typename P>
2162 inline void btree_node<P>::remove_values_ignore_children(
2163 int i, size_type to_erase, allocator_type *alloc) {
2164 params_type::move(alloc, slot(i + to_erase), slot(count()), slot(i));
2165 value_destroy_n(count() - to_erase, to_erase, alloc);
2166 set_count((field_type)(count() - to_erase));
2169 template <
typename P>
2170 void btree_node<P>::rebalance_right_to_left(
const int to_move,
2172 allocator_type *alloc) {
2173 assert(parent() == right->parent());
2174 assert(position() + 1 == right->position());
2175 assert(right->count() >= count());
2176 assert(to_move >= 1);
2177 assert(to_move <= right->count());
2180 value_init(count(), alloc, parent()->slot(position()));
2183 right->uninitialized_move_n(to_move - 1, 0, count() + 1,
this, alloc);
2186 params_type::move(alloc, right->slot(to_move - 1),
2187 parent()->slot(position()));
2190 params_type::move(alloc, right->slot(to_move), right->slot(right->count()),
2194 right->value_destroy_n(right->count() - to_move, to_move, alloc);
2198 for (
int i = 0; i < to_move; ++i) {
2199 init_child(count() + i + 1, right->child(i));
2201 for (
int i = 0; i <= right->count() - to_move; ++i) {
2202 assert(i + to_move <= right->max_count());
2203 right->init_child(i, right->child(i + to_move));
2204 right->clear_child(i + to_move);
2209 set_count((field_type)(count() + to_move));
2210 right->set_count((field_type)(right->count() - to_move));
2213 template <
typename P>
2214 void btree_node<P>::rebalance_left_to_right(
const int to_move,
2216 allocator_type *alloc) {
2217 assert(parent() == right->parent());
2218 assert(position() + 1 == right->position());
2219 assert(count() >= right->count());
2220 assert(to_move >= 1);
2221 assert(to_move <= count());
2229 if (right->count() >= to_move) {
2234 right->uninitialized_move_n(to_move, right->count() - to_move,
2235 right->count(), right, alloc);
2236 for (slot_type *src = right->slot(right->count() - to_move - 1),
2237 *dest = right->slot(right->count() - 1),
2238 *end = right->slot(0);
2239 src >= end; --src, --dest) {
2240 params_type::move(alloc, src, dest);
2244 params_type::move(alloc, parent()->slot(position()),
2245 right->slot(to_move - 1));
2248 params_type::move(alloc, slot(count() - (to_move - 1)), slot(count()),
2255 right->uninitialized_move_n(right->count(), 0, to_move, right, alloc);
2258 right->value_init(to_move - 1, alloc, parent()->slot(position()));
2261 const size_type uninitialized_remaining = to_move - right->count() - 1;
2262 uninitialized_move_n(uninitialized_remaining,
2263 count() - uninitialized_remaining, right->count(),
2265 params_type::move(alloc, slot(count() - (to_move - 1)),
2266 slot(count() - uninitialized_remaining), right->slot(0));
2270 params_type::move(alloc, slot(count() - to_move), parent()->slot(position()));
2273 value_destroy_n(count() - to_move, to_move, alloc);
2277 for (
int i = right->count(); i >= 0; --i) {
2278 right->init_child(i + to_move, right->child(i));
2279 right->clear_child(i);
2281 for (
int i = 1; i <= to_move; ++i) {
2282 right->init_child(i - 1, child(count() - to_move + i));
2283 clear_child(count() - to_move + i);
2288 set_count((field_type)(count() - to_move));
2289 right->set_count((field_type)(right->count() + to_move));
2292 template <
typename P>
2293 void btree_node<P>::split(
const int insert_position, btree_node *dest,
2294 allocator_type *alloc) {
2295 assert(dest->count() == 0);
2296 assert(max_count() == kNodeValues);
2302 if (insert_position == 0) {
2303 dest->set_count((field_type)(count() - 1));
2304 }
else if (insert_position == kNodeValues) {
2307 dest->set_count((field_type)(count() / 2));
2309 set_count((field_type)(count() - dest->count()));
2310 assert(count() >= 1);
2313 uninitialized_move_n(dest->count(), count(), 0, dest, alloc);
2316 value_destroy_n(count(), dest->count(), alloc);
2319 set_count((field_type)(count() - 1));
2320 parent()->emplace_value(position(), alloc, slot(count()));
2321 value_destroy(count(), alloc);
2322 parent()->init_child(position() + 1, dest);
2325 for (
int i = 0; i <= dest->count(); ++i) {
2326 assert(child(count() + i + 1) !=
nullptr);
2327 dest->init_child(i, child(count() + i + 1));
2328 clear_child(count() + i + 1);
2333 template <
typename P>
2334 void btree_node<P>::merge(btree_node *src, allocator_type *alloc) {
2335 assert(parent() == src->parent());
2336 assert(position() + 1 == src->position());
2339 value_init(count(), alloc, parent()->slot(position()));
2342 src->uninitialized_move_n(src->count(), 0, count() + 1,
this, alloc);
2345 src->value_destroy_n(0, src->count(), alloc);
2349 for (
int i = 0; i <= src->count(); ++i) {
2350 init_child(count() + i + 1, src->child(i));
2351 src->clear_child(i);
2356 set_count((field_type)(1 + count() + src->count()));
2360 parent()->remove_value(position(), alloc);
2363 template <
typename P>
2364 void btree_node<P>::swap(btree_node *x, allocator_type *alloc) {
2366 assert(leaf() == x->leaf());
2369 btree_node *smaller =
this, *larger = x;
2370 if (smaller->count() > larger->count()) {
2371 swap(smaller, larger);
2375 for (slot_type *a = smaller->slot(0), *b = larger->slot(0),
2376 *end = a + smaller->count();
2377 a != end; ++a, ++b) {
2378 params_type::swap(alloc, a, b);
2382 const size_type to_move = larger->count() - smaller->count();
2383 larger->uninitialized_move_n(to_move, smaller->count(), smaller->count(),
2385 larger->value_destroy_n(smaller->count(), to_move, alloc);
2389 std::swap_ranges(&smaller->mutable_child(0),
2390 &smaller->mutable_child(smaller->count() + 1),
2391 &larger->mutable_child(0));
2394 for (; i <= smaller->count(); ++i) {
2395 smaller->child(i)->set_parent(smaller);
2396 larger->child(i)->set_parent(larger);
2399 for (; i <= larger->count(); ++i) {
2400 smaller->init_child(i, larger->child(i));
2401 larger->clear_child(i);
2406 swap(mutable_count(), x->mutable_count());
2411 template <
typename N,
typename R,
typename P>
2412 void btree_iterator<N, R, P>::increment_slow() {
2414 assert(position >= node->count());
2415 btree_iterator save(*
this);
2416 while (position == node->count() && !node->is_root()) {
2417 assert(node->parent()->child(node->position()) == node);
2418 position = node->position();
2419 node = node->parent();
2421 if (position == node->count()) {
2425 assert(position < node->count());
2426 node = node->child(position + 1);
2427 while (!node->leaf()) {
2428 node = node->child(0);
2434 template <
typename N,
typename R,
typename P>
2435 void btree_iterator<N, R, P>::decrement_slow() {
2437 assert(position <= -1);
2438 btree_iterator save(*
this);
2439 while (position < 0 && !node->is_root()) {
2440 assert(node->parent()->child(node->position()) == node);
2441 position = node->position() - 1;
2442 node = node->parent();
2448 assert(position >= 0);
2449 node = node->child(position);
2450 while (!node->leaf()) {
2451 node = node->child(node->count());
2453 position = node->count() - 1;
2459 template <
typename P>
2460 template <
typename Btree>
2461 void btree<P>::copy_or_move_values_in_order(Btree *x) {
2462 static_assert(std::is_same<btree, Btree>::value ||
2463 std::is_same<const btree, Btree>::value,
2464 "Btree type must be same or const.");
2469 auto iter = x->begin();
2470 if (iter == x->end())
return;
2471 insert_multi(maybe_move_from_iterator(iter));
2473 for (; iter != x->end(); ++iter) {
2476 internal_emplace(end(), maybe_move_from_iterator(iter));
2480 template <
typename P>
2481 constexpr bool btree<P>::static_assert_validation() {
2482 static_assert(std::is_nothrow_copy_constructible<key_compare>::value,
2483 "Key comparison must be nothrow copy constructible");
2484 static_assert(std::is_nothrow_copy_constructible<allocator_type>::value,
2485 "Allocator must be nothrow copy constructible");
2486 static_assert(type_traits_internal::is_trivially_copyable<iterator>::value,
2487 "iterator not trivially copyable.");
2492 kNodeValues < (1 << (8 *
sizeof(
typename node_type::field_type))),
2493 "target node size too large");
2496 using compare_result_type =
2497 phmap::invoke_result_t<key_compare, key_type, key_type>;
2499 std::is_same<compare_result_type, bool>::value ||
2500 std::is_convertible<compare_result_type, phmap::weak_ordering>::value,
2501 "key comparison function must return phmap::{weak,strong}_ordering or "
2505 static_assert(node_type::MinimumOverhead() >=
sizeof(
void *) + 4,
2506 "node space assumption incorrect");
2511 template <
typename P>
2512 btree<P>::btree(
const key_compare &comp,
const allocator_type &alloc)
2513 : root_(comp, alloc, EmptyNode()), rightmost_(EmptyNode()), size_(0) {}
2515 template <
typename P>
2516 btree<P>::btree(
const btree &x) : btree(x.key_comp(), x.allocator()) {
2517 copy_or_move_values_in_order(&x);
2520 template <
typename P>
2521 template <
typename... Args>
2522 auto btree<P>::insert_unique(
const key_type &key, Args &&... args)
2523 -> std::pair<iterator, bool> {
2525 mutable_root() = rightmost_ = new_leaf_root_node(1);
2528 auto res = internal_locate(key);
2529 iterator &iter = res.value;
2531 if (res.HasMatch()) {
2534 return {iter,
false};
2537 iterator last = internal_last(iter);
2538 if (last.node && !compare_keys(key, last.key())) {
2540 return {last,
false};
2543 return {internal_emplace(iter, std::forward<Args>(args)...),
true};
2546 template <
typename P>
2547 template <
typename... Args>
2548 inline auto btree<P>::insert_hint_unique(iterator position,
const key_type &key,
2550 -> std::pair<iterator, bool> {
2552 if (position == end() || compare_keys(key, position.key())) {
2553 iterator prev = position;
2554 if (position == begin() || compare_keys((--prev).key(), key)) {
2556 return {internal_emplace(position, std::forward<Args>(args)...),
true};
2558 }
else if (compare_keys(position.key(), key)) {
2560 if (position == end() || compare_keys(key, position.key())) {
2562 return {internal_emplace(position, std::forward<Args>(args)...),
true};
2566 return {position,
false};
2569 return insert_unique(key, std::forward<Args>(args)...);
2572 template <
typename P>
2573 template <
typename InputIterator>
2574 void btree<P>::insert_iterator_unique(InputIterator b, InputIterator e) {
2575 for (; b != e; ++b) {
2576 insert_hint_unique(end(), params_type::key(*b), *b);
2580 template <
typename P>
2581 template <
typename ValueType>
2582 auto btree<P>::insert_multi(
const key_type &key, ValueType &&v) -> iterator {
2584 mutable_root() = rightmost_ = new_leaf_root_node(1);
2587 iterator iter = internal_upper_bound(key);
2588 if (iter.node ==
nullptr) {
2591 return internal_emplace(iter, std::forward<ValueType>(v));
2594 template <
typename P>
2595 template <
typename ValueType>
2596 auto btree<P>::insert_hint_multi(iterator position, ValueType &&v) -> iterator {
2598 const key_type &key = params_type::key(v);
2599 if (position == end() || !compare_keys(position.key(), key)) {
2600 iterator prev = position;
2601 if (position == begin() || !compare_keys(key, (--prev).key())) {
2603 return internal_emplace(position, std::forward<ValueType>(v));
2606 iterator next = position;
2608 if (next == end() || !compare_keys(next.key(), key)) {
2610 return internal_emplace(next, std::forward<ValueType>(v));
2614 return insert_multi(std::forward<ValueType>(v));
2617 template <
typename P>
2618 template <
typename InputIterator>
2619 void btree<P>::insert_iterator_multi(InputIterator b, InputIterator e) {
2620 for (; b != e; ++b) {
2621 insert_hint_multi(end(), *b);
2625 template <
typename P>
2626 auto btree<P>::operator=(
const btree &x) -> btree & {
2630 *mutable_key_comp() = x.key_comp();
2632 allocator_type>::propagate_on_container_copy_assignment::value) {
2633 *mutable_allocator() = x.allocator();
2636 copy_or_move_values_in_order(&x);
2641 template <
typename P>
2642 auto btree<P>::operator=(btree &&x)
noexcept -> btree & {
2648 allocator_type>::propagate_on_container_copy_assignment::value) {
2650 swap(root_, x.root_);
2651 swap(rightmost_, x.rightmost_);
2652 swap(size_, x.size_);
2654 if (allocator() == x.allocator()) {
2655 swap(mutable_root(), x.mutable_root());
2656 swap(*mutable_key_comp(), *x.mutable_key_comp());
2657 swap(rightmost_, x.rightmost_);
2658 swap(size_, x.size_);
2664 *mutable_key_comp() = x.key_comp();
2665 copy_or_move_values_in_order(&x);
2672 template <
typename P>
2673 auto btree<P>::erase(iterator iter) -> iterator {
2674 bool internal_delete =
false;
2675 if (!iter.node->leaf()) {
2680 iterator internal_iter(iter);
2682 assert(iter.node->leaf());
2683 params_type::move(mutable_allocator(), iter.node->slot(iter.position),
2684 internal_iter.node->slot(internal_iter.position));
2685 internal_delete =
true;
2689 iter.node->remove_value(iter.position, mutable_allocator());
2699 iterator res = rebalance_after_delete(iter);
2702 if (internal_delete) {
2708 template <
typename P>
2709 auto btree<P>::rebalance_after_delete(iterator iter) -> iterator {
2712 bool first_iteration =
true;
2714 if (iter.node == root()) {
2721 if (iter.node->count() >= kMinNodeValues) {
2724 bool merged = try_merge_or_rebalance(&iter);
2727 if (first_iteration) {
2729 first_iteration =
false;
2734 iter.position = iter.node->position();
2735 iter.node = iter.node->parent();
2740 if (res.position == res.node->count()) {
2741 res.position = res.node->count() - 1;
2748 template <
typename P>
2749 auto btree<P>::erase(iterator _begin, iterator _end)
2750 -> std::pair<size_type, iterator> {
2751 difference_type count = std::distance(_begin, _end);
2758 if (count == size_) {
2760 return {count, this->end()};
2763 if (_begin.node == _end.node) {
2764 erase_same_node(_begin, _end);
2766 return {count, rebalance_after_delete(_begin)};
2769 const size_type target_size = size_ - count;
2770 while (size_ > target_size) {
2771 if (_begin.node->leaf()) {
2772 const size_type remaining_to_erase = size_ - target_size;
2773 const size_type remaining_in_node = _begin.node->count() - _begin.position;
2774 _begin = erase_from_leaf_node(
2775 _begin, (std::min)(remaining_to_erase, remaining_in_node));
2777 _begin = erase(_begin);
2780 return {count, _begin};
2783 template <
typename P>
2784 void btree<P>::erase_same_node(iterator _begin, iterator _end) {
2785 assert(_begin.node == _end.node);
2786 assert(_end.position > _begin.position);
2788 node_type *node = _begin.node;
2789 size_type to_erase = _end.position - _begin.position;
2790 if (!node->leaf()) {
2792 for (size_type i = 0; i < to_erase; ++i) {
2793 internal_clear(node->child(_begin.position + i + 1));
2796 for (size_type i = _begin.position + to_erase + 1; i <= node->count(); ++i) {
2797 node->set_child(i - to_erase, node->child(i));
2798 node->clear_child(i);
2801 node->remove_values_ignore_children(_begin.position, to_erase,
2802 mutable_allocator());
2811 template <
typename P>
2812 auto btree<P>::erase_from_leaf_node(iterator _begin, size_type to_erase)
2814 node_type *node = _begin.node;
2815 assert(node->leaf());
2816 assert(node->count() > _begin.position);
2817 assert(_begin.position + to_erase <= node->count());
2819 node->remove_values_ignore_children(_begin.position, to_erase,
2820 mutable_allocator());
2824 return rebalance_after_delete(_begin);
2827 template <
typename P>
2828 template <
typename K>
2829 auto btree<P>::erase_unique(
const K &key) -> size_type {
2830 const iterator iter = internal_find(key);
2831 if (iter.node ==
nullptr) {
2839 template <
typename P>
2840 template <
typename K>
2841 auto btree<P>::erase_multi(
const K &key) -> size_type {
2842 const iterator _begin = internal_lower_bound(key);
2843 if (_begin.node ==
nullptr) {
2848 const iterator _end = internal_end(internal_upper_bound(key));
2849 return erase(_begin, _end).first;
2852 template <
typename P>
2853 void btree<P>::clear() {
2855 internal_clear(root());
2857 mutable_root() = EmptyNode();
2858 rightmost_ = EmptyNode();
2862 template <
typename P>
2863 void btree<P>::swap(btree &x) {
2866 allocator_type>::propagate_on_container_swap::value) {
2868 swap(root_, x.root_);
2871 assert(allocator() == x.allocator());
2872 swap(mutable_root(), x.mutable_root());
2873 swap(*mutable_key_comp(), *x.mutable_key_comp());
2875 swap(rightmost_, x.rightmost_);
2876 swap(size_, x.size_);
2879 template <
typename P>
2880 void btree<P>::verify()
const {
2881 assert(root() !=
nullptr);
2882 assert(leftmost() !=
nullptr);
2883 assert(rightmost_ !=
nullptr);
2884 assert(empty() || size() == internal_verify(root(),
nullptr,
nullptr));
2885 assert(leftmost() == (++const_iterator(root(), -1)).node);
2886 assert(rightmost_ == (--const_iterator(root(), root()->count())).node);
2887 assert(leftmost()->leaf());
2888 assert(rightmost_->leaf());
2891 template <
typename P>
2892 void btree<P>::rebalance_or_split(iterator *iter) {
2893 node_type *&node = iter->node;
2894 int &insert_position = iter->position;
2895 assert(node->count() == node->max_count());
2896 assert(kNodeValues == node->max_count());
2899 node_type *parent = node->parent();
2900 if (node != root()) {
2901 if (node->position() > 0) {
2903 node_type *left = parent->child(node->position() - 1);
2904 assert(left->max_count() == kNodeValues);
2905 if (left->count() < kNodeValues) {
2909 int to_move = (kNodeValues - left->count()) /
2910 (1 + (insert_position < kNodeValues));
2911 to_move = (std::max)(1, to_move);
2913 if (((insert_position - to_move) >= 0) ||
2914 ((left->count() + to_move) < kNodeValues)) {
2915 left->rebalance_right_to_left(to_move, node, mutable_allocator());
2917 assert(node->max_count() - node->count() == to_move);
2918 insert_position = insert_position - to_move;
2919 if (insert_position < 0) {
2920 insert_position = insert_position + left->count() + 1;
2924 assert(node->count() < node->max_count());
2930 if (node->position() < parent->count()) {
2932 node_type *right = parent->child(node->position() + 1);
2933 assert(right->max_count() == kNodeValues);
2934 if (right->count() < kNodeValues) {
2939 (kNodeValues - right->count()) / (1 + (insert_position > 0));
2940 to_move = (std::max)(1, to_move);
2942 if ((insert_position <= (node->count() - to_move)) ||
2943 ((right->count() + to_move) < kNodeValues)) {
2944 node->rebalance_left_to_right(to_move, right, mutable_allocator());
2946 if (insert_position > node->count()) {
2947 insert_position = insert_position - node->count() - 1;
2951 assert(node->count() < node->max_count());
2959 assert(parent->max_count() == kNodeValues);
2960 if (parent->count() == kNodeValues) {
2961 iterator parent_iter(node->parent(), node->position());
2962 rebalance_or_split(&parent_iter);
2968 parent = new_internal_node(parent);
2969 parent->init_child(0, root());
2970 mutable_root() = parent;
2972 assert(!parent->child(0)->leaf() || parent->child(0) == rightmost_);
2976 node_type *split_node;
2978 split_node = new_leaf_node(parent);
2979 node->split(insert_position, split_node, mutable_allocator());
2980 if (rightmost_ == node) rightmost_ = split_node;
2982 split_node = new_internal_node(parent);
2983 node->split(insert_position, split_node, mutable_allocator());
2986 if (insert_position > node->count()) {
2987 insert_position = insert_position - node->count() - 1;
2992 template <
typename P>
2993 void btree<P>::merge_nodes(node_type *left, node_type *right) {
2994 left->merge(right, mutable_allocator());
2995 if (right->leaf()) {
2996 if (rightmost_ == right) rightmost_ = left;
2997 delete_leaf_node(right);
2999 delete_internal_node(right);
3003 template <
typename P>
3004 bool btree<P>::try_merge_or_rebalance(iterator *iter) {
3005 node_type *parent = iter->node->parent();
3006 if (iter->node->position() > 0) {
3008 node_type *left = parent->child(iter->node->position() - 1);
3009 assert(left->max_count() == kNodeValues);
3010 if ((1 + left->count() + iter->node->count()) <= kNodeValues) {
3011 iter->position += 1 + left->count();
3012 merge_nodes(left, iter->node);
3017 if (iter->node->position() < parent->count()) {
3019 node_type *right = parent->child(iter->node->position() + 1);
3020 assert(right->max_count() == kNodeValues);
3021 if ((1 + iter->node->count() + right->count()) <= kNodeValues) {
3022 merge_nodes(iter->node, right);
3029 if ((right->count() > kMinNodeValues) &&
3030 ((iter->node->count() == 0) ||
3031 (iter->position > 0))) {
3032 int to_move = (right->count() - iter->node->count()) / 2;
3033 to_move = (std::min)(to_move, right->count() - 1);
3034 iter->node->rebalance_right_to_left(to_move, right, mutable_allocator());
3038 if (iter->node->position() > 0) {
3043 node_type *left = parent->child(iter->node->position() - 1);
3044 if ((left->count() > kMinNodeValues) &&
3045 ((iter->node->count() == 0) ||
3046 (iter->position < iter->node->count()))) {
3047 int to_move = (left->count() - iter->node->count()) / 2;
3048 to_move = (std::min)(to_move, left->count() - 1);
3049 left->rebalance_left_to_right(to_move, iter->node, mutable_allocator());
3050 iter->position += to_move;
3057 template <
typename P>
3058 void btree<P>::try_shrink() {
3059 if (root()->count() > 0) {
3063 if (root()->leaf()) {
3064 assert(size() == 0);
3065 delete_leaf_node(root());
3066 mutable_root() = EmptyNode();
3067 rightmost_ = EmptyNode();
3069 node_type *child = root()->child(0);
3071 delete_internal_node(root());
3072 mutable_root() = child;
3076 template <
typename P>
3077 template <
typename IterType>
3078 inline IterType btree<P>::internal_last(IterType iter) {
3079 assert(iter.node !=
nullptr);
3080 while (iter.position == iter.node->count()) {
3081 iter.position = iter.node->position();
3082 iter.node = iter.node->parent();
3083 if (iter.node->leaf()) {
3084 iter.node =
nullptr;
3091 template <
typename P>
3092 template <
typename... Args>
3093 inline auto btree<P>::internal_emplace(iterator iter, Args &&... args)
3095 if (!iter.node->leaf()) {
3101 const int max_count = iter.node->max_count();
3102 if (iter.node->count() == max_count) {
3104 if (max_count < kNodeValues) {
3107 assert(iter.node == root());
3109 new_leaf_root_node((std::min<int>)(kNodeValues, 2 * max_count));
3110 iter.node->swap(root(), mutable_allocator());
3111 delete_leaf_node(root());
3112 mutable_root() = iter.node;
3113 rightmost_ = iter.node;
3115 rebalance_or_split(&iter);
3118 iter.node->emplace_value(iter.position, mutable_allocator(),
3119 std::forward<Args>(args)...);
3124 template <
typename P>
3125 template <
typename K>
3126 inline auto btree<P>::internal_locate(
const K &key)
const
3127 -> SearchResult<iterator, is_key_compare_to::value> {
3128 return internal_locate_impl(key, is_key_compare_to());
3131 template <
typename P>
3132 template <
typename K>
3133 inline auto btree<P>::internal_locate_impl(
3134 const K &key, std::false_type )
const
3135 -> SearchResult<iterator, false> {
3136 iterator iter(
const_cast<node_type *
>(root()), 0);
3138 iter.position = iter.node->lower_bound(key, key_comp()).value;
3143 if (iter.node->leaf()) {
3146 iter.node = iter.node->child(iter.position);
3151 template <
typename P>
3152 template <
typename K>
3153 inline auto btree<P>::internal_locate_impl(
3154 const K &key, std::true_type )
const
3155 -> SearchResult<iterator, true> {
3156 iterator iter(
const_cast<node_type *
>(root()), 0);
3158 SearchResult<int, true> res = iter.node->lower_bound(key, key_comp());
3159 iter.position = res.value;
3160 if (res.match == MatchKind::kEq) {
3161 return {iter, MatchKind::kEq};
3163 if (iter.node->leaf()) {
3166 iter.node = iter.node->child(iter.position);
3168 return {iter, MatchKind::kNe};
3171 template <
typename P>
3172 template <
typename K>
3173 auto btree<P>::internal_lower_bound(
const K &key)
const -> iterator {
3174 iterator iter(
const_cast<node_type *
>(root()), 0);
3176 iter.position = iter.node->lower_bound(key, key_comp()).value;
3177 if (iter.node->leaf()) {
3180 iter.node = iter.node->child(iter.position);
3182 return internal_last(iter);
3185 template <
typename P>
3186 template <
typename K>
3187 auto btree<P>::internal_upper_bound(
const K &key)
const -> iterator {
3188 iterator iter(
const_cast<node_type *
>(root()), 0);
3190 iter.position = iter.node->upper_bound(key, key_comp());
3191 if (iter.node->leaf()) {
3194 iter.node = iter.node->child(iter.position);
3196 return internal_last(iter);
3199 template <
typename P>
3200 template <
typename K>
3201 auto btree<P>::internal_find(
const K &key)
const -> iterator {
3202 auto res = internal_locate(key);
3203 if (res.HasMatch()) {
3208 const iterator iter = internal_last(res.value);
3209 if (iter.node !=
nullptr && !compare_keys(key, iter.key())) {
3213 return {
nullptr, 0};
3216 template <
typename P>
3217 void btree<P>::internal_clear(node_type *node) {
3218 if (!node->leaf()) {
3219 for (
int i = 0; i <= node->count(); ++i) {
3220 internal_clear(node->child(i));
3222 delete_internal_node(node);
3224 delete_leaf_node(node);
3228 template <
typename P>
3229 int btree<P>::internal_verify(
3230 const node_type *node,
const key_type *lo,
const key_type *hi)
const {
3231 assert(node->count() > 0);
3232 assert(node->count() <= node->max_count());
3234 assert(!compare_keys(node->key(0), *lo));
3237 assert(!compare_keys(*hi, node->key(node->count() - 1)));
3239 for (
int i = 1; i < node->count(); ++i) {
3240 assert(!compare_keys(node->key(i), node->key(i - 1)));
3242 int count = node->count();
3243 if (!node->leaf()) {
3244 for (
int i = 0; i <= node->count(); ++i) {
3245 assert(node->child(i) !=
nullptr);
3246 assert(node->child(i)->parent() == node);
3247 assert(node->child(i)->position() == i);
3248 count += internal_verify(
3250 (i == 0) ? lo : &node->key(i - 1),
3251 (i == node->count()) ? hi : &node->key(i));
3259 template <
typename Tree>
3260 class btree_container {
3261 using params_type =
typename Tree::params_type;
3270 typename KeyArg<IsTransparent<typename Tree::key_compare>::value>::
3271 template type<K, typename Tree::key_type>;
3274 using key_type =
typename Tree::key_type;
3275 using value_type =
typename Tree::value_type;
3276 using size_type =
typename Tree::size_type;
3277 using difference_type =
typename Tree::difference_type;
3278 using key_compare =
typename Tree::key_compare;
3279 using value_compare =
typename Tree::value_compare;
3280 using allocator_type =
typename Tree::allocator_type;
3281 using reference =
typename Tree::reference;
3282 using const_reference =
typename Tree::const_reference;
3283 using pointer =
typename Tree::pointer;
3284 using const_pointer =
typename Tree::const_pointer;
3285 using iterator =
typename Tree::iterator;
3286 using const_iterator =
typename Tree::const_iterator;
3287 using reverse_iterator =
typename Tree::reverse_iterator;
3288 using const_reverse_iterator =
typename Tree::const_reverse_iterator;
3289 using node_type =
typename Tree::node_handle_type;
3292 btree_container() : tree_(key_compare(), allocator_type()) {}
3293 explicit btree_container(
const key_compare &comp,
3294 const allocator_type &alloc = allocator_type())
3295 : tree_(comp, alloc) {}
3296 btree_container(
const btree_container &x) =
default;
3297 btree_container(btree_container &&x)
noexcept =
default;
3298 btree_container &operator=(
const btree_container &x) =
default;
3299 btree_container &operator=(btree_container &&x)
noexcept(
3300 std::is_nothrow_move_assignable<Tree>::value) =
default;
3303 iterator begin() {
return tree_.begin(); }
3304 const_iterator begin()
const {
return tree_.begin(); }
3305 const_iterator cbegin()
const {
return tree_.begin(); }
3306 iterator end() {
return tree_.end(); }
3307 const_iterator end()
const {
return tree_.end(); }
3308 const_iterator cend()
const {
return tree_.end(); }
3309 reverse_iterator rbegin() {
return tree_.rbegin(); }
3310 const_reverse_iterator rbegin()
const {
return tree_.rbegin(); }
3311 const_reverse_iterator crbegin()
const {
return tree_.rbegin(); }
3312 reverse_iterator rend() {
return tree_.rend(); }
3313 const_reverse_iterator rend()
const {
return tree_.rend(); }
3314 const_reverse_iterator crend()
const {
return tree_.rend(); }
3317 template <
typename K = key_type>
3318 iterator find(
const key_arg<K> &key) {
3319 return tree_.find(key);
3321 template <
typename K = key_type>
3322 const_iterator find(
const key_arg<K> &key)
const {
return tree_.find(key); }
3324 template <
typename K = key_type>
3325 bool contains(
const key_arg<K> &key)
const {
return find(key) != end(); }
3327 template <
typename K = key_type>
3328 iterator lower_bound(
const key_arg<K> &key) {
return tree_.lower_bound(key); }
3330 template <
typename K = key_type>
3331 const_iterator lower_bound(
const key_arg<K> &key)
const {
return tree_.lower_bound(key); }
3333 template <
typename K = key_type>
3334 iterator upper_bound(
const key_arg<K> &key) {
return tree_.upper_bound(key); }
3336 template <
typename K = key_type>
3337 const_iterator upper_bound(
const key_arg<K> &key)
const {
return tree_.upper_bound(key); }
3339 template <
typename K = key_type>
3340 std::pair<iterator, iterator> equal_range(
const key_arg<K> &key) {
return tree_.equal_range(key); }
3342 template <
typename K = key_type>
3343 std::pair<const_iterator, const_iterator> equal_range(
3344 const key_arg<K> &key)
const {
3345 return tree_.equal_range(key);
3348 iterator erase(const_iterator iter) {
return tree_.erase(iterator(iter)); }
3349 iterator erase(iterator iter) {
return tree_.erase(iter); }
3350 iterator erase(const_iterator first, const_iterator last) {
3351 return tree_.erase(iterator(first), iterator(last)).second;
3354 node_type extract(iterator position) {
3357 auto node = CommonAccess::Move<node_type>(get_allocator(), position.slot());
3362 node_type extract(const_iterator position) {
3363 return extract(iterator(position));
3367 void clear() { tree_.clear(); }
3368 void swap(btree_container &x) { tree_.swap(x.tree_); }
3369 void verify()
const { tree_.verify(); }
3371 size_type size()
const {
return tree_.size(); }
3372 size_type max_size()
const {
return tree_.max_size(); }
3373 bool empty()
const {
return tree_.empty(); }
3375 friend bool operator==(
const btree_container &x,
const btree_container &y) {
3376 if (x.size() != y.size())
return false;
3377 return std::equal(x.begin(), x.end(), y.begin());
3380 friend bool operator!=(
const btree_container &x,
const btree_container &y) {
return !(x == y); }
3382 friend bool operator<(
const btree_container &x,
const btree_container &y) {
3383 return std::lexicographical_compare(x.begin(), x.end(), y.begin(), y.end());
3386 friend bool operator>(
const btree_container &x,
const btree_container &y) {
return y < x; }
3388 friend bool operator<=(
const btree_container &x,
const btree_container &y) {
return !(y < x); }
3390 friend bool operator>=(
const btree_container &x,
const btree_container &y) {
return !(x < y); }
3393 allocator_type get_allocator()
const {
return tree_.get_allocator(); }
3396 key_compare key_comp()
const {
return tree_.key_comp(); }
3397 value_compare value_comp()
const {
return tree_.value_comp(); }
3400 template <
typename State>
3401 friend State AbslHashValue(State h,
const btree_container &b) {
3402 for (
const auto &v : b) {
3403 h = State::combine(std::move(h), v);
3405 return State::combine(std::move(h), b.size());
3414 template <
typename Tree>
3415 class btree_set_container :
public btree_container<Tree> {
3416 using super_type = btree_container<Tree>;
3417 using params_type =
typename Tree::params_type;
3418 using init_type =
typename params_type::init_type;
3419 using is_key_compare_to =
typename params_type::is_key_compare_to;
3420 friend class BtreeNodePeer;
3424 using key_arg =
typename super_type::template key_arg<K>;
3427 using key_type =
typename Tree::key_type;
3428 using value_type =
typename Tree::value_type;
3429 using size_type =
typename Tree::size_type;
3430 using key_compare =
typename Tree::key_compare;
3431 using allocator_type =
typename Tree::allocator_type;
3432 using iterator =
typename Tree::iterator;
3433 using const_iterator =
typename Tree::const_iterator;
3434 using node_type =
typename super_type::node_type;
3435 using insert_return_type = InsertReturnType<iterator, node_type>;
3436 using super_type::super_type;
3437 btree_set_container() {}
3439 template <
class InputIterator>
3440 btree_set_container(InputIterator b, InputIterator e,
3441 const key_compare &comp = key_compare(),
3442 const allocator_type &alloc = allocator_type())
3443 : super_type(comp, alloc) {
3447 btree_set_container(std::initializer_list<init_type> init,
3448 const key_compare &comp = key_compare(),
3449 const allocator_type &alloc = allocator_type())
3450 : btree_set_container(init.begin(), init.end(), comp, alloc) {}
3453 template <
typename K = key_type>
3454 size_type count(
const key_arg<K> &key)
const {
3455 return this->tree_.count_unique(key);
3459 std::pair<iterator, bool> insert(
const value_type &x) {
3460 return this->tree_.insert_unique(params_type::key(x), x);
3462 std::pair<iterator, bool> insert(value_type &&x) {
3463 return this->tree_.insert_unique(params_type::key(x), std::move(x));
3465 template <
typename... Args>
3466 std::pair<iterator, bool> emplace(Args &&... args) {
3467 init_type v(std::forward<Args>(args)...);
3468 return this->tree_.insert_unique(params_type::key(v), std::move(v));
3470 iterator insert(const_iterator position,
const value_type &x) {
3472 .insert_hint_unique(iterator(position), params_type::key(x), x)
3475 iterator insert(const_iterator position, value_type &&x) {
3477 .insert_hint_unique(iterator(position), params_type::key(x),
3482 template <
typename... Args>
3483 iterator emplace_hint(const_iterator position, Args &&... args) {
3484 init_type v(std::forward<Args>(args)...);
3486 .insert_hint_unique(iterator(position), params_type::key(v),
3491 template <
typename InputIterator>
3492 void insert(InputIterator b, InputIterator e) {
3493 this->tree_.insert_iterator_unique(b, e);
3496 void insert(std::initializer_list<init_type> init) {
3497 this->tree_.insert_iterator_unique(init.begin(), init.end());
3500 insert_return_type insert(node_type &&node) {
3501 if (!node)
return {this->end(),
false, node_type()};
3502 std::pair<iterator, bool> res =
3503 this->tree_.insert_unique(params_type::key(CommonAccess::GetSlot(node)),
3504 CommonAccess::GetSlot(node));
3506 CommonAccess::Destroy(&node);
3507 return {res.first,
true, node_type()};
3509 return {res.first,
false, std::move(node)};
3513 iterator insert(const_iterator hint, node_type &&node) {
3514 if (!node)
return this->end();
3515 std::pair<iterator, bool> res = this->tree_.insert_hint_unique(
3516 iterator(hint), params_type::key(CommonAccess::GetSlot(node)),
3517 CommonAccess::GetSlot(node));
3518 if (res.second) CommonAccess::Destroy(&node);
3522 template <
typename K = key_type>
3523 size_type erase(
const key_arg<K> &key) {
return this->tree_.erase_unique(key); }
3524 using super_type::erase;
3526 template <
typename K = key_type>
3527 node_type extract(
const key_arg<K> &key) {
3528 auto it = this->find(key);
3529 return it == this->end() ? node_type() : extract(it);
3532 using super_type::extract;
3539 typename phmap::enable_if_t<
3541 std::is_same<value_type, typename T::value_type>,
3542 std::is_same<allocator_type, typename T::allocator_type>,
3543 std::is_same<
typename params_type::is_map_container,
3544 typename T::params_type::is_map_container>>::value,
3546 void merge(btree_container<T> &src) {
3547 for (
auto src_it = src.begin(); src_it != src.end();) {
3548 if (insert(std::move(*src_it)).second) {
3549 src_it = src.erase(src_it);
3558 typename phmap::enable_if_t<
3560 std::is_same<value_type, typename T::value_type>,
3561 std::is_same<allocator_type, typename T::allocator_type>,
3562 std::is_same<
typename params_type::is_map_container,
3563 typename T::params_type::is_map_container>>::value,
3565 void merge(btree_container<T> &&src) {
3572 template <
typename Tree>
3573 class btree_map_container :
public btree_set_container<Tree> {
3574 using super_type = btree_set_container<Tree>;
3575 using params_type =
typename Tree::params_type;
3579 using key_arg =
typename super_type::template key_arg<K>;
3582 using key_type =
typename Tree::key_type;
3583 using mapped_type =
typename params_type::mapped_type;
3584 using value_type =
typename Tree::value_type;
3585 using key_compare =
typename Tree::key_compare;
3586 using allocator_type =
typename Tree::allocator_type;
3587 using iterator =
typename Tree::iterator;
3588 using const_iterator =
typename Tree::const_iterator;
3591 using super_type::super_type;
3592 btree_map_container() {}
3595 template <
typename... Args>
3596 std::pair<iterator, bool> try_emplace(
const key_type &k, Args &&... args) {
3597 return this->tree_.insert_unique(
3598 k, std::piecewise_construct, std::forward_as_tuple(k),
3599 std::forward_as_tuple(std::forward<Args>(args)...));
3601 template <
typename... Args>
3602 std::pair<iterator, bool> try_emplace(key_type &&k, Args &&... args) {
3607 const key_type& key_ref = k;
3608 return this->tree_.insert_unique(
3609 key_ref, std::piecewise_construct, std::forward_as_tuple(std::move(k)),
3610 std::forward_as_tuple(std::forward<Args>(args)...));
3612 template <
typename... Args>
3613 iterator try_emplace(const_iterator hint,
const key_type &k,
3616 .insert_hint_unique(iterator(hint), k, std::piecewise_construct,
3617 std::forward_as_tuple(k),
3618 std::forward_as_tuple(std::forward<Args>(args)...))
3621 template <
typename... Args>
3622 iterator try_emplace(const_iterator hint, key_type &&k, Args &&... args) {
3627 const key_type& key_ref = k;
3629 .insert_hint_unique(iterator(hint), key_ref, std::piecewise_construct,
3630 std::forward_as_tuple(std::move(k)),
3631 std::forward_as_tuple(std::forward<Args>(args)...))
3634 mapped_type &operator[](
const key_type &k) {
3635 return try_emplace(k).first->second;
3637 mapped_type &operator[](key_type &&k) {
3638 return try_emplace(std::move(k)).first->second;
3641 template <
typename K = key_type>
3642 mapped_type &at(
const key_arg<K> &key) {
3643 auto it = this->find(key);
3644 if (it == this->end())
3645 base_internal::ThrowStdOutOfRange(
"phmap::btree_map::at");
3648 template <
typename K = key_type>
3649 const mapped_type &at(
const key_arg<K> &key)
const {
3650 auto it = this->find(key);
3651 if (it == this->end())
3652 base_internal::ThrowStdOutOfRange(
"phmap::btree_map::at");
3658 template <
typename Tree>
3659 class btree_multiset_container :
public btree_container<Tree> {
3660 using super_type = btree_container<Tree>;
3661 using params_type =
typename Tree::params_type;
3662 using init_type =
typename params_type::init_type;
3663 using is_key_compare_to =
typename params_type::is_key_compare_to;
3666 using key_arg =
typename super_type::template key_arg<K>;
3669 using key_type =
typename Tree::key_type;
3670 using value_type =
typename Tree::value_type;
3671 using size_type =
typename Tree::size_type;
3672 using key_compare =
typename Tree::key_compare;
3673 using allocator_type =
typename Tree::allocator_type;
3674 using iterator =
typename Tree::iterator;
3675 using const_iterator =
typename Tree::const_iterator;
3676 using node_type =
typename super_type::node_type;
3679 using super_type::super_type;
3680 btree_multiset_container() {}
3683 template <
class InputIterator>
3684 btree_multiset_container(InputIterator b, InputIterator e,
3685 const key_compare &comp = key_compare(),
3686 const allocator_type &alloc = allocator_type())
3687 : super_type(comp, alloc) {
3692 btree_multiset_container(std::initializer_list<init_type> init,
3693 const key_compare &comp = key_compare(),
3694 const allocator_type &alloc = allocator_type())
3695 : btree_multiset_container(init.begin(), init.end(), comp, alloc) {}
3698 template <
typename K = key_type>
3699 size_type count(
const key_arg<K> &key)
const {
3700 return this->tree_.count_multi(key);
3704 iterator insert(
const value_type &x) {
return this->tree_.insert_multi(x); }
3705 iterator insert(value_type &&x) {
3706 return this->tree_.insert_multi(std::move(x));
3708 iterator insert(const_iterator position,
const value_type &x) {
3709 return this->tree_.insert_hint_multi(iterator(position), x);
3711 iterator insert(const_iterator position, value_type &&x) {
3712 return this->tree_.insert_hint_multi(iterator(position), std::move(x));
3714 template <
typename InputIterator>
3715 void insert(InputIterator b, InputIterator e) {
3716 this->tree_.insert_iterator_multi(b, e);
3718 void insert(std::initializer_list<init_type> init) {
3719 this->tree_.insert_iterator_multi(init.begin(), init.end());
3721 template <
typename... Args>
3722 iterator emplace(Args &&... args) {
3723 return this->tree_.insert_multi(init_type(std::forward<Args>(args)...));
3725 template <
typename... Args>
3726 iterator emplace_hint(const_iterator position, Args &&... args) {
3727 return this->tree_.insert_hint_multi(
3728 iterator(position), init_type(std::forward<Args>(args)...));
3730 iterator insert(node_type &&node) {
3731 if (!node)
return this->end();
3733 this->tree_.insert_multi(params_type::key(CommonAccess::GetSlot(node)),
3734 CommonAccess::GetSlot(node));
3735 CommonAccess::Destroy(&node);
3738 iterator insert(const_iterator hint, node_type &&node) {
3739 if (!node)
return this->end();
3740 iterator res = this->tree_.insert_hint_multi(
3742 std::move(params_type::element(CommonAccess::GetSlot(node))));
3743 CommonAccess::Destroy(&node);
3748 template <
typename K = key_type>
3749 size_type erase(
const key_arg<K> &key) {
3750 return this->tree_.erase_multi(key);
3752 using super_type::erase;
3755 template <
typename K = key_type>
3756 node_type extract(
const key_arg<K> &key) {
3757 auto it = this->find(key);
3758 return it == this->end() ? node_type() : extract(it);
3760 using super_type::extract;
3766 typename phmap::enable_if_t<
3768 std::is_same<value_type, typename T::value_type>,
3769 std::is_same<allocator_type, typename T::allocator_type>,
3770 std::is_same<
typename params_type::is_map_container,
3771 typename T::params_type::is_map_container>>::value,
3773 void merge(btree_container<T> &src) {
3774 insert(std::make_move_iterator(src.begin()),
3775 std::make_move_iterator(src.end()));
3781 typename phmap::enable_if_t<
3783 std::is_same<value_type, typename T::value_type>,
3784 std::is_same<allocator_type, typename T::allocator_type>,
3785 std::is_same<
typename params_type::is_map_container,
3786 typename T::params_type::is_map_container>>::value,
3788 void merge(btree_container<T> &&src) {
3794 template <
typename Tree>
3795 class btree_multimap_container :
public btree_multiset_container<Tree> {
3796 using super_type = btree_multiset_container<Tree>;
3797 using params_type =
typename Tree::params_type;
3800 using mapped_type =
typename params_type::mapped_type;
3803 using super_type::super_type;
3804 btree_multimap_container() {}
3814 template <
typename Key,
typename Compare,
typename Alloc>
3815 class btree_set :
public priv::btree_set_container<
3816 priv::btree<priv::set_params<
3817 Key, Compare, Alloc, 256, false>>>
3819 using Base =
typename btree_set::btree_set_container;
3829 using Base::max_size;
3834 using Base::emplace;
3835 using Base::emplace_hint;
3836 using Base::extract;
3839 using Base::contains;
3841 using Base::equal_range;
3843 using Base::get_allocator;
3844 using Base::key_comp;
3845 using Base::value_comp;
3850 template <
typename K,
typename C,
typename A>
3851 void swap(btree_set<K, C, A> &x, btree_set<K, C, A> &y) {
3857 template <
typename K,
typename C,
typename A,
typename Pred>
3858 void erase_if(btree_set<K, C, A> &set, Pred pred) {
3859 for (
auto it = set.begin(); it != set.end();) {
3871 template <
typename Key,
typename Compare,
typename Alloc>
3872 class btree_multiset :
public priv::btree_multiset_container<
3873 priv::btree<priv::set_params<
3874 Key, Compare, Alloc, 256, true>>>
3876 using Base =
typename btree_multiset::btree_multiset_container;
3886 using Base::max_size;
3891 using Base::emplace;
3892 using Base::emplace_hint;
3893 using Base::extract;
3896 using Base::contains;
3898 using Base::equal_range;
3900 using Base::get_allocator;
3901 using Base::key_comp;
3902 using Base::value_comp;
3907 template <
typename K,
typename C,
typename A>
3908 void swap(btree_multiset<K, C, A> &x, btree_multiset<K, C, A> &y) {
3914 template <
typename K,
typename C,
typename A,
typename Pred>
3915 void erase_if(btree_multiset<K, C, A> &set, Pred pred) {
3916 for (
auto it = set.begin(); it != set.end();) {
3929 template <
typename Key,
typename Value,
typename Compare,
typename Alloc>
3930 class btree_map :
public priv::btree_map_container<
3931 priv::btree<priv::map_params<
3932 Key, Value, Compare, Alloc, 256, false>>>
3934 using Base =
typename btree_map::btree_map_container;
3944 using Base::max_size;
3949 using Base::emplace;
3950 using Base::emplace_hint;
3951 using Base::try_emplace;
3952 using Base::extract;
3956 using Base::contains;
3958 using Base::equal_range;
3960 using Base::operator[];
3961 using Base::get_allocator;
3962 using Base::key_comp;
3963 using Base::value_comp;
3968 template <
typename K,
typename V,
typename C,
typename A>
3969 void swap(btree_map<K, V, C, A> &x, btree_map<K, V, C, A> &y) {
3974 template <
typename K,
typename V,
typename C,
typename A,
typename Pred>
3975 void erase_if(btree_map<K, V, C, A> &map, Pred pred) {
3976 for (
auto it = map.begin(); it != map.end();) {
3988 template <
typename Key,
typename Value,
typename Compare,
typename Alloc>
3989 class btree_multimap :
public priv::btree_multimap_container<
3990 priv::btree<priv::map_params<
3991 Key, Value, Compare, Alloc, 256, true>>>
3993 using Base =
typename btree_multimap::btree_multimap_container;
4003 using Base::max_size;
4008 using Base::emplace;
4009 using Base::emplace_hint;
4010 using Base::extract;
4013 using Base::contains;
4015 using Base::equal_range;
4017 using Base::get_allocator;
4018 using Base::key_comp;
4019 using Base::value_comp;
4024 template <
typename K,
typename V,
typename C,
typename A>
4025 void swap(btree_multimap<K, V, C, A> &x, btree_multimap<K, V, C, A> &y) {
4031 template <
typename K,
typename V,
typename C,
typename A,
typename Pred>
4032 void erase_if(btree_multimap<K, V, C, A> &map, Pred pred) {
4033 for (
auto it = map.begin(); it != map.end();) {
4046 #pragma warning(pop)
Definition phmap_base.h:4293
int8 int8_t
Definition fwd.hpp:43
uint8 uint8_t
Definition fwd.hpp:103
uint16 uint16_t
Definition fwd.hpp:117
Definition phmap_base.h:85
Definition phmap_base.h:1379
Definition phmap_base.h:200
Definition phmap_base.h:163
Definition phmap_base.h:168
Definition phmap_base.h:242
Definition phmap_base.h:95
Definition phmap_base.h:134