btree.h 96 KB

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