btree.h 94 KB

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