btree.h 114 KB

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