You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

btree.h 107 kB

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