foa.hpp 67 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213
  1. /* Fast open-addressing hash table.
  2. *
  3. * Copyright 2022-2023 Joaquin M Lopez Munoz.
  4. * Copyright 2023 Christian Mazakas.
  5. * Distributed under the Boost Software License, Version 1.0.
  6. * (See accompanying file LICENSE_1_0.txt or copy at
  7. * http://www.boost.org/LICENSE_1_0.txt)
  8. *
  9. * See https://www.boost.org/libs/unordered for library home page.
  10. */
  11. #ifndef BOOST_UNORDERED_DETAIL_FOA_HPP
  12. #define BOOST_UNORDERED_DETAIL_FOA_HPP
  13. #include <boost/assert.hpp>
  14. #include <boost/config.hpp>
  15. #include <boost/config/workaround.hpp>
  16. #include <boost/core/allocator_traits.hpp>
  17. #include <boost/core/bit.hpp>
  18. #include <boost/core/empty_value.hpp>
  19. #include <boost/core/no_exceptions_support.hpp>
  20. #include <boost/core/pointer_traits.hpp>
  21. #include <boost/cstdint.hpp>
  22. #include <boost/predef.h>
  23. #include <boost/type_traits/has_trivial_copy.hpp>
  24. #include <boost/type_traits/is_nothrow_swappable.hpp>
  25. #include <boost/unordered/detail/narrow_cast.hpp>
  26. #include <boost/unordered/detail/xmx.hpp>
  27. #include <boost/unordered/detail/mulx.hpp>
  28. #include <boost/unordered/hash_traits.hpp>
  29. #include <climits>
  30. #include <cmath>
  31. #include <cstddef>
  32. #include <cstring>
  33. #include <iterator>
  34. #include <limits>
  35. #include <memory>
  36. #include <tuple>
  37. #include <type_traits>
  38. #include <utility>
  39. #if !defined(BOOST_UNORDERED_DISABLE_SSE2)
  40. #if defined(BOOST_UNORDERED_ENABLE_SSE2)|| \
  41. defined(__SSE2__)|| \
  42. defined(_M_X64)||(defined(_M_IX86_FP)&&_M_IX86_FP>=2)
  43. #define BOOST_UNORDERED_SSE2
  44. #endif
  45. #endif
  46. #if !defined(BOOST_UNORDERED_DISABLE_NEON)
  47. #if defined(BOOST_UNORDERED_ENABLE_NEON)||\
  48. (defined(__ARM_NEON)&&!defined(__ARM_BIG_ENDIAN))
  49. #define BOOST_UNORDERED_LITTLE_ENDIAN_NEON
  50. #endif
  51. #endif
  52. #if defined(BOOST_UNORDERED_SSE2)
  53. #include <emmintrin.h>
  54. #elif defined(BOOST_UNORDERED_LITTLE_ENDIAN_NEON)
  55. #include <arm_neon.h>
  56. #endif
  57. #ifdef __has_builtin
  58. #define BOOST_UNORDERED_HAS_BUILTIN(x) __has_builtin(x)
  59. #else
  60. #define BOOST_UNORDERED_HAS_BUILTIN(x) 0
  61. #endif
  62. #if !defined(NDEBUG)
  63. #define BOOST_UNORDERED_ASSUME(cond) BOOST_ASSERT(cond)
  64. #elif BOOST_UNORDERED_HAS_BUILTIN(__builtin_assume)
  65. #define BOOST_UNORDERED_ASSUME(cond) __builtin_assume(cond)
  66. #elif defined(__GNUC__) || BOOST_UNORDERED_HAS_BUILTIN(__builtin_unreachable)
  67. #define BOOST_UNORDERED_ASSUME(cond) \
  68. do{ \
  69. if(!(cond))__builtin_unreachable(); \
  70. }while(0)
  71. #elif defined(_MSC_VER)
  72. #define BOOST_UNORDERED_ASSUME(cond) __assume(cond)
  73. #else
  74. #define BOOST_UNORDERED_ASSUME(cond) \
  75. do{ \
  76. static_cast<void>(false&&(cond)); \
  77. }while(0)
  78. #endif
  79. #define BOOST_UNORDERED_STATIC_ASSERT_HASH_PRED(Hash, Pred) \
  80. static_assert(boost::is_nothrow_swappable<Hash>::value, \
  81. "Template parameter Hash is required to be nothrow Swappable."); \
  82. static_assert(boost::is_nothrow_swappable<Pred>::value, \
  83. "Template parameter Pred is required to be nothrow Swappable");
  84. namespace boost{
  85. namespace unordered{
  86. namespace detail{
  87. namespace foa{
  88. static const std::size_t default_bucket_count = 0;
  89. /* foa::table is an open-addressing hash table serving as the foundational core
  90. * of boost::unordered_flat_[map|set]. Its main internal design aspects are:
  91. *
  92. * - Element slots are logically split into groups of size N=15. The number
  93. * of groups is always a power of two, so the number of allocated slots
  94. is of the form (N*2^n)-1 (final slot reserved for a sentinel mark).
  95. * - Positioning is done at the group level rather than the slot level, that
  96. * is, for any given element its hash value is used to locate a group and
  97. * insertion is performed on the first available element of that group;
  98. * if the group is full (overflow), further groups are tried using
  99. * quadratic probing.
  100. * - Each group has an associated 16B metadata word holding reduced hash
  101. * values and overflow information. Reduced hash values are used to
  102. * accelerate lookup within the group by using 128-bit SIMD or 64-bit word
  103. * operations.
  104. */
  105. /* group15 controls metadata information of a group of N=15 element slots.
  106. * The 16B metadata word is organized as follows (LSB depicted rightmost):
  107. *
  108. * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  109. * |ofw|h14|h13|h13|h11|h10|h09|h08|h07|h06|h05|h04|h03|h02|h01|h00|
  110. * +---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+---+
  111. *
  112. * hi is 0 if the i-th element slot is avalaible, 1 to mark a sentinel and,
  113. * when the slot is occupied, a value in the range [2,255] obtained from the
  114. * element's original hash value.
  115. * ofw is the so-called overflow byte. If insertion of an element with hash
  116. * value h is tried on a full group, then the (h%8)-th bit of the overflow
  117. * byte is set to 1 and a further group is probed. Having an overflow byte
  118. * brings two advantages:
  119. *
  120. * - There's no need to reserve a special value of hi to mark tombstone
  121. * slots; each reduced hash value keeps then log2(254)=7.99 bits of the
  122. * original hash (alternative approaches reserve one full bit to mark
  123. * if the slot is available/deleted, so their reduced hash values are 7 bit
  124. * strong only).
  125. * - When doing an unsuccessful lookup (i.e. the element is not present in
  126. * the table), probing stops at the first non-overflowed group. Having 8
  127. * bits for signalling overflow makes it very likely that we stop at the
  128. * current group (this happens when no element with the same (h%8) value
  129. * has overflowed in the group), saving us an additional group check even
  130. * under high-load/high-erase conditions. It is critical that hash
  131. * reduction is invariant under modulo 8 (see maybe_caused_overflow).
  132. *
  133. * When looking for an element with hash value h, match(h) returns a bitmask
  134. * signalling which slots have the same reduced hash value. If available,
  135. * match uses SSE2 or (little endian) Neon 128-bit SIMD operations. On non-SIMD
  136. * scenarios, the logical layout described above is physically mapped to two
  137. * 64-bit words with *bit interleaving*, i.e. the least significant 16 bits of
  138. * the first 64-bit word contain the least significant bits of each byte in the
  139. * "logical" 128-bit word, and so forth. With this layout, match can be
  140. * implemented with 4 ANDs, 3 shifts, 2 XORs, 1 OR and 1 NOT.
  141. *
  142. * group15 has no user-defined ctor so that it's a trivial type and can be
  143. * initialized via memset etc. Where needed, group15::initialize sets the
  144. * metadata to all zeros.
  145. */
  146. #if defined(BOOST_UNORDERED_SSE2)
  147. struct group15
  148. {
  149. static constexpr int N=15;
  150. struct dummy_group_type
  151. {
  152. alignas(16) unsigned char storage[N+1]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
  153. };
  154. inline void initialize(){m=_mm_setzero_si128();}
  155. inline void set(std::size_t pos,std::size_t hash)
  156. {
  157. BOOST_ASSERT(pos<N);
  158. at(pos)=reduced_hash(hash);
  159. }
  160. inline void set_sentinel()
  161. {
  162. at(N-1)=sentinel_;
  163. }
  164. inline bool is_sentinel(std::size_t pos)const
  165. {
  166. BOOST_ASSERT(pos<N);
  167. return at(pos)==sentinel_;
  168. }
  169. inline void reset(std::size_t pos)
  170. {
  171. BOOST_ASSERT(pos<N);
  172. at(pos)=available_;
  173. }
  174. static inline void reset(unsigned char* pc)
  175. {
  176. *pc=available_;
  177. }
  178. inline int match(std::size_t hash)const
  179. {
  180. return _mm_movemask_epi8(
  181. _mm_cmpeq_epi8(m,_mm_set1_epi32(match_word(hash))))&0x7FFF;
  182. }
  183. inline bool is_not_overflowed(std::size_t hash)const
  184. {
  185. static constexpr unsigned char shift[]={1,2,4,8,16,32,64,128};
  186. return !(overflow()&shift[hash%8]);
  187. }
  188. inline void mark_overflow(std::size_t hash)
  189. {
  190. #if BOOST_WORKAROUND(BOOST_GCC, >= 50000 && BOOST_GCC < 60000)
  191. overflow() = static_cast<unsigned char>( overflow() | static_cast<unsigned char>(1<<(hash%8)) );
  192. #else
  193. overflow()|=static_cast<unsigned char>(1<<(hash%8));
  194. #endif
  195. }
  196. static inline bool maybe_caused_overflow(unsigned char* pc)
  197. {
  198. std::size_t pos=reinterpret_cast<uintptr_t>(pc)%sizeof(group15);
  199. group15 *pg=reinterpret_cast<group15*>(pc-pos);
  200. return !pg->is_not_overflowed(*pc);
  201. };
  202. inline int match_available()const
  203. {
  204. return _mm_movemask_epi8(
  205. _mm_cmpeq_epi8(m,_mm_setzero_si128()))&0x7FFF;
  206. }
  207. inline int match_occupied()const
  208. {
  209. return (~match_available())&0x7FFF;
  210. }
  211. inline int match_really_occupied()const /* excluding sentinel */
  212. {
  213. return at(N-1)==sentinel_?match_occupied()&0x3FFF:match_occupied();
  214. }
  215. private:
  216. static constexpr unsigned char available_=0,
  217. sentinel_=1;
  218. inline static int match_word(std::size_t hash)
  219. {
  220. static constexpr boost::uint32_t word[]=
  221. {
  222. 0x08080808u,0x09090909u,0x02020202u,0x03030303u,0x04040404u,0x05050505u,0x06060606u,0x07070707u,
  223. 0x08080808u,0x09090909u,0x0A0A0A0Au,0x0B0B0B0Bu,0x0C0C0C0Cu,0x0D0D0D0Du,0x0E0E0E0Eu,0x0F0F0F0Fu,
  224. 0x10101010u,0x11111111u,0x12121212u,0x13131313u,0x14141414u,0x15151515u,0x16161616u,0x17171717u,
  225. 0x18181818u,0x19191919u,0x1A1A1A1Au,0x1B1B1B1Bu,0x1C1C1C1Cu,0x1D1D1D1Du,0x1E1E1E1Eu,0x1F1F1F1Fu,
  226. 0x20202020u,0x21212121u,0x22222222u,0x23232323u,0x24242424u,0x25252525u,0x26262626u,0x27272727u,
  227. 0x28282828u,0x29292929u,0x2A2A2A2Au,0x2B2B2B2Bu,0x2C2C2C2Cu,0x2D2D2D2Du,0x2E2E2E2Eu,0x2F2F2F2Fu,
  228. 0x30303030u,0x31313131u,0x32323232u,0x33333333u,0x34343434u,0x35353535u,0x36363636u,0x37373737u,
  229. 0x38383838u,0x39393939u,0x3A3A3A3Au,0x3B3B3B3Bu,0x3C3C3C3Cu,0x3D3D3D3Du,0x3E3E3E3Eu,0x3F3F3F3Fu,
  230. 0x40404040u,0x41414141u,0x42424242u,0x43434343u,0x44444444u,0x45454545u,0x46464646u,0x47474747u,
  231. 0x48484848u,0x49494949u,0x4A4A4A4Au,0x4B4B4B4Bu,0x4C4C4C4Cu,0x4D4D4D4Du,0x4E4E4E4Eu,0x4F4F4F4Fu,
  232. 0x50505050u,0x51515151u,0x52525252u,0x53535353u,0x54545454u,0x55555555u,0x56565656u,0x57575757u,
  233. 0x58585858u,0x59595959u,0x5A5A5A5Au,0x5B5B5B5Bu,0x5C5C5C5Cu,0x5D5D5D5Du,0x5E5E5E5Eu,0x5F5F5F5Fu,
  234. 0x60606060u,0x61616161u,0x62626262u,0x63636363u,0x64646464u,0x65656565u,0x66666666u,0x67676767u,
  235. 0x68686868u,0x69696969u,0x6A6A6A6Au,0x6B6B6B6Bu,0x6C6C6C6Cu,0x6D6D6D6Du,0x6E6E6E6Eu,0x6F6F6F6Fu,
  236. 0x70707070u,0x71717171u,0x72727272u,0x73737373u,0x74747474u,0x75757575u,0x76767676u,0x77777777u,
  237. 0x78787878u,0x79797979u,0x7A7A7A7Au,0x7B7B7B7Bu,0x7C7C7C7Cu,0x7D7D7D7Du,0x7E7E7E7Eu,0x7F7F7F7Fu,
  238. 0x80808080u,0x81818181u,0x82828282u,0x83838383u,0x84848484u,0x85858585u,0x86868686u,0x87878787u,
  239. 0x88888888u,0x89898989u,0x8A8A8A8Au,0x8B8B8B8Bu,0x8C8C8C8Cu,0x8D8D8D8Du,0x8E8E8E8Eu,0x8F8F8F8Fu,
  240. 0x90909090u,0x91919191u,0x92929292u,0x93939393u,0x94949494u,0x95959595u,0x96969696u,0x97979797u,
  241. 0x98989898u,0x99999999u,0x9A9A9A9Au,0x9B9B9B9Bu,0x9C9C9C9Cu,0x9D9D9D9Du,0x9E9E9E9Eu,0x9F9F9F9Fu,
  242. 0xA0A0A0A0u,0xA1A1A1A1u,0xA2A2A2A2u,0xA3A3A3A3u,0xA4A4A4A4u,0xA5A5A5A5u,0xA6A6A6A6u,0xA7A7A7A7u,
  243. 0xA8A8A8A8u,0xA9A9A9A9u,0xAAAAAAAAu,0xABABABABu,0xACACACACu,0xADADADADu,0xAEAEAEAEu,0xAFAFAFAFu,
  244. 0xB0B0B0B0u,0xB1B1B1B1u,0xB2B2B2B2u,0xB3B3B3B3u,0xB4B4B4B4u,0xB5B5B5B5u,0xB6B6B6B6u,0xB7B7B7B7u,
  245. 0xB8B8B8B8u,0xB9B9B9B9u,0xBABABABAu,0xBBBBBBBBu,0xBCBCBCBCu,0xBDBDBDBDu,0xBEBEBEBEu,0xBFBFBFBFu,
  246. 0xC0C0C0C0u,0xC1C1C1C1u,0xC2C2C2C2u,0xC3C3C3C3u,0xC4C4C4C4u,0xC5C5C5C5u,0xC6C6C6C6u,0xC7C7C7C7u,
  247. 0xC8C8C8C8u,0xC9C9C9C9u,0xCACACACAu,0xCBCBCBCBu,0xCCCCCCCCu,0xCDCDCDCDu,0xCECECECEu,0xCFCFCFCFu,
  248. 0xD0D0D0D0u,0xD1D1D1D1u,0xD2D2D2D2u,0xD3D3D3D3u,0xD4D4D4D4u,0xD5D5D5D5u,0xD6D6D6D6u,0xD7D7D7D7u,
  249. 0xD8D8D8D8u,0xD9D9D9D9u,0xDADADADAu,0xDBDBDBDBu,0xDCDCDCDCu,0xDDDDDDDDu,0xDEDEDEDEu,0xDFDFDFDFu,
  250. 0xE0E0E0E0u,0xE1E1E1E1u,0xE2E2E2E2u,0xE3E3E3E3u,0xE4E4E4E4u,0xE5E5E5E5u,0xE6E6E6E6u,0xE7E7E7E7u,
  251. 0xE8E8E8E8u,0xE9E9E9E9u,0xEAEAEAEAu,0xEBEBEBEBu,0xECECECECu,0xEDEDEDEDu,0xEEEEEEEEu,0xEFEFEFEFu,
  252. 0xF0F0F0F0u,0xF1F1F1F1u,0xF2F2F2F2u,0xF3F3F3F3u,0xF4F4F4F4u,0xF5F5F5F5u,0xF6F6F6F6u,0xF7F7F7F7u,
  253. 0xF8F8F8F8u,0xF9F9F9F9u,0xFAFAFAFAu,0xFBFBFBFBu,0xFCFCFCFCu,0xFDFDFDFDu,0xFEFEFEFEu,0xFFFFFFFFu,
  254. };
  255. return (int)word[narrow_cast<unsigned char>(hash)];
  256. }
  257. inline static unsigned char reduced_hash(std::size_t hash)
  258. {
  259. return narrow_cast<unsigned char>(match_word(hash));
  260. }
  261. inline unsigned char& at(std::size_t pos)
  262. {
  263. return reinterpret_cast<unsigned char*>(&m)[pos];
  264. }
  265. inline unsigned char at(std::size_t pos)const
  266. {
  267. return reinterpret_cast<const unsigned char*>(&m)[pos];
  268. }
  269. inline unsigned char& overflow()
  270. {
  271. return at(N);
  272. }
  273. inline unsigned char overflow()const
  274. {
  275. return at(N);
  276. }
  277. alignas(16) __m128i m;
  278. };
  279. #elif defined(BOOST_UNORDERED_LITTLE_ENDIAN_NEON)
  280. struct group15
  281. {
  282. static constexpr int N=15;
  283. struct dummy_group_type
  284. {
  285. alignas(16) unsigned char storage[N+1]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0};
  286. };
  287. inline void initialize(){m=vdupq_n_s8(0);}
  288. inline void set(std::size_t pos,std::size_t hash)
  289. {
  290. BOOST_ASSERT(pos<N);
  291. at(pos)=reduced_hash(hash);
  292. }
  293. inline void set_sentinel()
  294. {
  295. at(N-1)=sentinel_;
  296. }
  297. inline bool is_sentinel(std::size_t pos)const
  298. {
  299. BOOST_ASSERT(pos<N);
  300. return pos==N-1&&at(N-1)==sentinel_;
  301. }
  302. inline void reset(std::size_t pos)
  303. {
  304. BOOST_ASSERT(pos<N);
  305. at(pos)=available_;
  306. }
  307. static inline void reset(unsigned char* pc)
  308. {
  309. *pc=available_;
  310. }
  311. inline int match(std::size_t hash)const
  312. {
  313. return simde_mm_movemask_epi8(vceqq_s8(
  314. m,vdupq_n_s8(static_cast<signed char>(reduced_hash(hash)))))&0x7FFF;
  315. }
  316. inline bool is_not_overflowed(std::size_t hash)const
  317. {
  318. static constexpr unsigned char shift[]={1,2,4,8,16,32,64,128};
  319. return !(overflow()&shift[hash%8]);
  320. }
  321. inline void mark_overflow(std::size_t hash)
  322. {
  323. overflow()|=static_cast<unsigned char>(1<<(hash%8));
  324. }
  325. static inline bool maybe_caused_overflow(unsigned char* pc)
  326. {
  327. std::size_t pos=reinterpret_cast<uintptr_t>(pc)%sizeof(group15);
  328. group15 *pg=reinterpret_cast<group15*>(pc-pos);
  329. return !pg->is_not_overflowed(*pc);
  330. };
  331. inline int match_available()const
  332. {
  333. return simde_mm_movemask_epi8(vceqq_s8(m,vdupq_n_s8(0)))&0x7FFF;
  334. }
  335. inline int match_occupied()const
  336. {
  337. return simde_mm_movemask_epi8(
  338. vcgtq_u8(vreinterpretq_u8_s8(m),vdupq_n_u8(0)))&0x7FFF;
  339. }
  340. inline int match_really_occupied()const /* excluding sentinel */
  341. {
  342. return at(N-1)==sentinel_?match_occupied()&0x3FFF:match_occupied();
  343. }
  344. private:
  345. static constexpr unsigned char available_=0,
  346. sentinel_=1;
  347. inline static unsigned char reduced_hash(std::size_t hash)
  348. {
  349. static constexpr unsigned char table[]={
  350. 8,9,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  351. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  352. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  353. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  354. 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  355. 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
  356. 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  357. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
  358. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  359. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  360. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  361. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  362. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  363. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  364. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  365. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  366. };
  367. return table[(unsigned char)hash];
  368. }
  369. /* Copied from
  370. * https://github.com/simd-everywhere/simde/blob/master/simde/x86/sse2.h#L3763
  371. */
  372. static inline int simde_mm_movemask_epi8(uint8x16_t a)
  373. {
  374. static constexpr uint8_t md[16]={
  375. 1 << 0, 1 << 1, 1 << 2, 1 << 3,
  376. 1 << 4, 1 << 5, 1 << 6, 1 << 7,
  377. 1 << 0, 1 << 1, 1 << 2, 1 << 3,
  378. 1 << 4, 1 << 5, 1 << 6, 1 << 7,
  379. };
  380. uint8x16_t masked=vandq_u8(vld1q_u8(md),a);
  381. uint8x8x2_t tmp=vzip_u8(vget_low_u8(masked),vget_high_u8(masked));
  382. uint16x8_t x=vreinterpretq_u16_u8(vcombine_u8(tmp.val[0],tmp.val[1]));
  383. #if defined(__ARM_ARCH_ISA_A64)
  384. return vaddvq_u16(x);
  385. #else
  386. uint64x2_t t64=vpaddlq_u32(vpaddlq_u16(x));
  387. return int(vgetq_lane_u64(t64,0))+int(vgetq_lane_u64(t64,1));
  388. #endif
  389. }
  390. inline unsigned char& at(std::size_t pos)
  391. {
  392. return reinterpret_cast<unsigned char*>(&m)[pos];
  393. }
  394. inline unsigned char at(std::size_t pos)const
  395. {
  396. return reinterpret_cast<const unsigned char*>(&m)[pos];
  397. }
  398. inline unsigned char& overflow()
  399. {
  400. return at(N);
  401. }
  402. inline unsigned char overflow()const
  403. {
  404. return at(N);
  405. }
  406. alignas(16) int8x16_t m;
  407. };
  408. #else /* non-SIMD */
  409. struct group15
  410. {
  411. static constexpr int N=15;
  412. struct dummy_group_type
  413. {
  414. alignas(16) boost::uint64_t m[2]=
  415. {0x0000000000004000ull,0x0000000000000000ull};
  416. };
  417. inline void initialize(){m[0]=0;m[1]=0;}
  418. inline void set(std::size_t pos,std::size_t hash)
  419. {
  420. BOOST_ASSERT(pos<N);
  421. set_impl(pos,reduced_hash(hash));
  422. }
  423. inline void set_sentinel()
  424. {
  425. set_impl(N-1,sentinel_);
  426. }
  427. inline bool is_sentinel(std::size_t pos)const
  428. {
  429. BOOST_ASSERT(pos<N);
  430. return
  431. pos==N-1&&
  432. (m[0] & boost::uint64_t(0x4000400040004000ull))==boost::uint64_t(0x4000ull)&&
  433. (m[1] & boost::uint64_t(0x4000400040004000ull))==0;
  434. }
  435. inline void reset(std::size_t pos)
  436. {
  437. BOOST_ASSERT(pos<N);
  438. set_impl(pos,available_);
  439. }
  440. static inline void reset(unsigned char* pc)
  441. {
  442. std::size_t pos=reinterpret_cast<uintptr_t>(pc)%sizeof(group15);
  443. pc-=pos;
  444. reinterpret_cast<group15*>(pc)->reset(pos);
  445. }
  446. inline int match(std::size_t hash)const
  447. {
  448. return match_impl(reduced_hash(hash));
  449. }
  450. inline bool is_not_overflowed(std::size_t hash)const
  451. {
  452. return !(reinterpret_cast<const boost::uint16_t*>(m)[hash%8] & 0x8000u);
  453. }
  454. inline void mark_overflow(std::size_t hash)
  455. {
  456. reinterpret_cast<boost::uint16_t*>(m)[hash%8]|=0x8000u;
  457. }
  458. static inline bool maybe_caused_overflow(unsigned char* pc)
  459. {
  460. std::size_t pos=reinterpret_cast<uintptr_t>(pc)%sizeof(group15);
  461. group15 *pg=reinterpret_cast<group15*>(pc-pos);
  462. boost::uint64_t x=((pg->m[0])>>pos)&0x000100010001ull;
  463. boost::uint32_t y=narrow_cast<boost::uint32_t>(x|(x>>15)|(x>>30));
  464. return !pg->is_not_overflowed(y);
  465. };
  466. inline int match_available()const
  467. {
  468. boost::uint64_t x=~(m[0]|m[1]);
  469. boost::uint32_t y=static_cast<boost::uint32_t>(x&(x>>32));
  470. y&=y>>16;
  471. return y&0x7FFF;
  472. }
  473. inline int match_occupied()const
  474. {
  475. boost::uint64_t x=m[0]|m[1];
  476. boost::uint32_t y=narrow_cast<boost::uint32_t>(x|(x>>32));
  477. y|=y>>16;
  478. return y&0x7FFF;
  479. }
  480. inline int match_really_occupied()const /* excluding sentinel */
  481. {
  482. return ~(match_impl(0)|match_impl(1))&0x7FFF;
  483. }
  484. private:
  485. static constexpr unsigned char available_=0,
  486. sentinel_=1;
  487. inline static unsigned char reduced_hash(std::size_t hash)
  488. {
  489. static constexpr unsigned char table[]={
  490. 8,9,2,3,4,5,6,7,8,9,10,11,12,13,14,15,
  491. 16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,
  492. 32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,
  493. 48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,
  494. 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,
  495. 80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,
  496. 96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111,
  497. 112,113,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
  498. 128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,
  499. 144,145,146,147,148,149,150,151,152,153,154,155,156,157,158,159,
  500. 160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,
  501. 176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,
  502. 192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,
  503. 208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,
  504. 224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,
  505. 240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,
  506. };
  507. return table[narrow_cast<unsigned char>(hash)];
  508. }
  509. inline void set_impl(std::size_t pos,std::size_t n)
  510. {
  511. BOOST_ASSERT(n<256);
  512. set_impl(m[0],pos,n&0xFu);
  513. set_impl(m[1],pos,n>>4);
  514. }
  515. static inline void set_impl(boost::uint64_t& x,std::size_t pos,std::size_t n)
  516. {
  517. static constexpr boost::uint64_t mask[]=
  518. {
  519. 0x0000000000000000ull,0x0000000000000001ull,0x0000000000010000ull,
  520. 0x0000000000010001ull,0x0000000100000000ull,0x0000000100000001ull,
  521. 0x0000000100010000ull,0x0000000100010001ull,0x0001000000000000ull,
  522. 0x0001000000000001ull,0x0001000000010000ull,0x0001000000010001ull,
  523. 0x0001000100000000ull,0x0001000100000001ull,0x0001000100010000ull,
  524. 0x0001000100010001ull,
  525. };
  526. static constexpr boost::uint64_t imask[]=
  527. {
  528. 0x0001000100010001ull,0x0001000100010000ull,0x0001000100000001ull,
  529. 0x0001000100000000ull,0x0001000000010001ull,0x0001000000010000ull,
  530. 0x0001000000000001ull,0x0001000000000000ull,0x0000000100010001ull,
  531. 0x0000000100010000ull,0x0000000100000001ull,0x0000000100000000ull,
  532. 0x0000000000010001ull,0x0000000000010000ull,0x0000000000000001ull,
  533. 0x0000000000000000ull,
  534. };
  535. BOOST_ASSERT(pos<16&&n<16);
  536. x|= mask[n]<<pos;
  537. x&=~(imask[n]<<pos);
  538. }
  539. inline int match_impl(std::size_t n)const
  540. {
  541. static constexpr boost::uint64_t mask[]=
  542. {
  543. 0x0000000000000000ull,0x000000000000ffffull,0x00000000ffff0000ull,
  544. 0x00000000ffffffffull,0x0000ffff00000000ull,0x0000ffff0000ffffull,
  545. 0x0000ffffffff0000ull,0x0000ffffffffffffull,0xffff000000000000ull,
  546. 0xffff00000000ffffull,0xffff0000ffff0000ull,0xffff0000ffffffffull,
  547. 0xffffffff00000000ull,0xffffffff0000ffffull,0xffffffffffff0000ull,
  548. 0xffffffffffffffffull,
  549. };
  550. BOOST_ASSERT(n<256);
  551. boost::uint64_t x=m[0]^mask[n&0xFu];
  552. x=~((m[1]^mask[n>>4])|x);
  553. boost::uint32_t y=static_cast<boost::uint32_t>(x&(x>>32));
  554. y&=y>>16;
  555. return y&0x7FFF;
  556. }
  557. alignas(16) boost::uint64_t m[2];
  558. };
  559. #endif
  560. /* foa::table uses a size policy to obtain the permissible sizes of the group
  561. * array (and, by implication, the element array) and to do the hash->group
  562. * mapping.
  563. *
  564. * - size_index(n) returns an unspecified "index" number used in other policy
  565. * operations.
  566. * - size(size_index_) returns the number of groups for the given index. It is
  567. * guaranteed that size(size_index(n)) >= n.
  568. * - min_size() is the minimum number of groups permissible, i.e.
  569. * size(size_index(0)).
  570. * - position(hash,size_index_) maps hash to a position in the range
  571. * [0,size(size_index_)).
  572. *
  573. * The reason we're introducing the intermediate index value for calculating
  574. * sizes and positions is that it allows us to optimize the implementation of
  575. * position, which is in the hot path of lookup and insertion operations:
  576. * pow2_size_policy, the actual size policy used by foa::table, returns 2^n
  577. * (n>0) as permissible sizes and returns the n most significant bits
  578. * of the hash value as the position in the group array; using a size index
  579. * defined as i = (bits in std::size_t) - n, we have an unbeatable
  580. * implementation of position(hash) as hash>>i.
  581. * There's a twofold reason for choosing the high bits of hash for positioning:
  582. * - Multiplication-based mixing tends to yield better entropy in the high
  583. * part of its result.
  584. * - group15 reduced-hash values take the *low* bits of hash, and we want
  585. * these values and positioning to be as uncorrelated as possible.
  586. */
  587. struct pow2_size_policy
  588. {
  589. static inline std::size_t size_index(std::size_t n)
  590. {
  591. // TODO: min size is 2, see if we can bring it down to 1 without loss
  592. // of performance
  593. return sizeof(std::size_t)*CHAR_BIT-
  594. (n<=2?1:((std::size_t)(boost::core::bit_width(n-1))));
  595. }
  596. static inline std::size_t size(std::size_t size_index_)
  597. {
  598. return std::size_t(1)<<(sizeof(std::size_t)*CHAR_BIT-size_index_);
  599. }
  600. static constexpr std::size_t min_size(){return 2;}
  601. static inline std::size_t position(std::size_t hash,std::size_t size_index_)
  602. {
  603. return hash>>size_index_;
  604. }
  605. };
  606. /* size index of a group array for a given *element* capacity */
  607. template<typename Group,typename SizePolicy>
  608. static inline std::size_t size_index_for(std::size_t n)
  609. {
  610. /* n/N+1 == ceil((n+1)/N) (extra +1 for the sentinel) */
  611. return SizePolicy::size_index(n/Group::N+1);
  612. }
  613. /* Quadratic prober over a power-of-two range using triangular numbers.
  614. * mask in next(mask) must be the range size minus one (and since size is 2^n,
  615. * mask has exactly its n first bits set to 1).
  616. */
  617. struct pow2_quadratic_prober
  618. {
  619. pow2_quadratic_prober(std::size_t pos_):pos{pos_}{}
  620. inline std::size_t get()const{return pos;}
  621. /* next returns false when the whole array has been traversed, which ends
  622. * probing (in practice, full-table probing will only happen with very small
  623. * arrays).
  624. */
  625. inline bool next(std::size_t mask)
  626. {
  627. step+=1;
  628. pos=(pos+step)&mask;
  629. return step<=mask;
  630. }
  631. private:
  632. std::size_t pos,step=0;
  633. };
  634. /* Mixing policies: no_mix is the identity function, xmx_mix uses the
  635. * xmx function defined in <boost/unordered/detail/xmx.hpp>, and mulx_mix
  636. * uses the mulx function from <boost/unordered/detail/mulx.hpp>.
  637. *
  638. * foa::table mixes hash results with mulx_mix unless the hash is marked as
  639. * avalanching, i.e. of good quality (see <boost/unordered/hash_traits.hpp>).
  640. */
  641. struct no_mix
  642. {
  643. template<typename Hash,typename T>
  644. static inline std::size_t mix(const Hash& h,const T& x)
  645. {
  646. return h(x);
  647. }
  648. };
  649. struct xmx_mix
  650. {
  651. template<typename Hash,typename T>
  652. static inline std::size_t mix(const Hash& h,const T& x)
  653. {
  654. return xmx(h(x));
  655. }
  656. };
  657. struct mulx_mix
  658. {
  659. template<typename Hash,typename T>
  660. static inline std::size_t mix(const Hash& h,const T& x)
  661. {
  662. return mulx(h(x));
  663. }
  664. };
  665. /* boost::core::countr_zero has a potentially costly check for
  666. * the case x==0.
  667. */
  668. inline unsigned int unchecked_countr_zero(int x)
  669. {
  670. #if defined(BOOST_MSVC)
  671. unsigned long r;
  672. _BitScanForward(&r,(unsigned long)x);
  673. return (unsigned int)r;
  674. #else
  675. BOOST_UNORDERED_ASSUME(x!=0);
  676. return (unsigned int)boost::core::countr_zero((unsigned int)x);
  677. #endif
  678. }
  679. template<typename,typename,typename,typename>
  680. class table;
  681. /* table_iterator keeps two pointers:
  682. *
  683. * - A pointer p to the element slot.
  684. * - A pointer pc to the n-th byte of the associated group metadata, where n
  685. * is the position of the element in the group.
  686. *
  687. * A simpler solution would have been to keep a pointer p to the element, a
  688. * pointer pg to the group, and the position n, but that would increase
  689. * sizeof(table_iterator) by 4/8 bytes. In order to make this compact
  690. * representation feasible, it is required that group objects are aligned
  691. * to their size, so that we can recover pg and n as
  692. *
  693. * - n = pc%sizeof(group)
  694. * - pg = pc-n
  695. *
  696. * (for explanatory purposes pg and pc are treated above as if they were memory
  697. * addresses rather than pointers).The main drawback of this two-pointer
  698. * representation is that iterator increment is relatively slow.
  699. *
  700. * p = nullptr is conventionally used to mark end() iterators.
  701. */
  702. /* internal conversion from const_iterator to iterator */
  703. class const_iterator_cast_tag {};
  704. template<typename TypePolicy,typename Group,bool Const>
  705. class table_iterator
  706. {
  707. using type_policy=TypePolicy;
  708. using table_element_type=typename type_policy::element_type;
  709. public:
  710. using difference_type=std::ptrdiff_t;
  711. using value_type=typename type_policy::value_type;
  712. using pointer=
  713. typename std::conditional<Const,value_type const*,value_type*>::type;
  714. using reference=
  715. typename std::conditional<Const,value_type const&,value_type&>::type;
  716. using iterator_category=std::forward_iterator_tag;
  717. using element_type=
  718. typename std::conditional<Const,value_type const,value_type>::type;
  719. table_iterator()=default;
  720. template<bool Const2,typename std::enable_if<!Const2>::type* =nullptr>
  721. table_iterator(const table_iterator<TypePolicy,Group,Const2>& x):
  722. pc{x.pc},p{x.p}{}
  723. table_iterator(
  724. const_iterator_cast_tag, const table_iterator<TypePolicy,Group,true>& x):
  725. pc{x.pc},p{x.p}{}
  726. inline reference operator*()const noexcept{return type_policy::value_from(*p);}
  727. inline pointer operator->()const noexcept
  728. {return std::addressof(type_policy::value_from(*p));}
  729. inline table_iterator& operator++()noexcept{increment();return *this;}
  730. inline table_iterator operator++(int)noexcept
  731. {auto x=*this;increment();return x;}
  732. friend inline bool operator==(
  733. const table_iterator& x,const table_iterator& y)
  734. {return x.p==y.p;}
  735. friend inline bool operator!=(
  736. const table_iterator& x,const table_iterator& y)
  737. {return !(x==y);}
  738. private:
  739. template<typename,typename,bool> friend class table_iterator;
  740. template<typename,typename,typename,typename> friend class table;
  741. table_iterator(Group* pg,std::size_t n,const table_element_type* p_):
  742. pc{reinterpret_cast<unsigned char*>(const_cast<Group*>(pg))+n},
  743. p{const_cast<table_element_type*>(p_)}
  744. {}
  745. inline std::size_t rebase() noexcept
  746. {
  747. std::size_t off=reinterpret_cast<uintptr_t>(pc)%sizeof(Group);
  748. pc-=off;
  749. return off;
  750. }
  751. inline void increment()noexcept
  752. {
  753. std::size_t n0=rebase();
  754. int mask=(reinterpret_cast<Group*>(pc)->match_occupied()>>(n0+1))<<(n0+1);
  755. if(!mask){
  756. do{
  757. pc+=sizeof(Group);
  758. p+=Group::N;
  759. }
  760. while((mask=reinterpret_cast<Group*>(pc)->match_occupied())==0);
  761. }
  762. auto n=unchecked_countr_zero(mask);
  763. if(BOOST_UNLIKELY(reinterpret_cast<Group*>(pc)->is_sentinel(n))){
  764. p=nullptr;
  765. }
  766. else{
  767. pc+=n;
  768. p-=n0;
  769. p+=n;
  770. }
  771. }
  772. unsigned char *pc=nullptr;
  773. table_element_type *p=nullptr;
  774. };
  775. /* table_arrays controls allocation, initialization and deallocation of
  776. * paired arrays of groups and element slots. Only one chunk of memory is
  777. * allocated to place both arrays: this is not done for efficiency reasons,
  778. * but in order to be able to properly align the group array without storing
  779. * additional offset information --the alignment required (16B) is usually
  780. * greater than alignof(std::max_align_t) and thus not guaranteed by
  781. * allocators.
  782. */
  783. template<typename Group,std::size_t Size>
  784. Group* dummy_groups()
  785. {
  786. /* Dummy storage initialized as if in an empty container (actually, each
  787. * of its groups is initialized like a separate empty container).
  788. * We make table_arrays::groups point to this when capacity()==0, so that
  789. * we are not allocating any dynamic memory and yet lookup can be implemented
  790. * without checking for groups==nullptr. This space won't ever be used for
  791. * insertion as the container's capacity is precisely zero.
  792. */
  793. static constexpr typename Group::dummy_group_type
  794. storage[Size]={typename Group::dummy_group_type(),};
  795. return reinterpret_cast<Group*>(
  796. const_cast<typename Group::dummy_group_type*>(storage));
  797. }
  798. template<typename Value,typename Group,typename SizePolicy>
  799. struct table_arrays
  800. {
  801. using value_type=Value;
  802. using group_type=Group;
  803. static constexpr auto N=group_type::N;
  804. using size_policy=SizePolicy;
  805. template<typename Allocator>
  806. static table_arrays new_(Allocator& al,std::size_t n)
  807. {
  808. using storage_allocator=
  809. typename boost::allocator_rebind<Allocator, Value>::type;
  810. using storage_traits=boost::allocator_traits<storage_allocator>;
  811. auto groups_size_index=size_index_for<group_type,size_policy>(n);
  812. auto groups_size=size_policy::size(groups_size_index);
  813. table_arrays arrays{groups_size_index,groups_size-1,nullptr,nullptr};
  814. if(!n){
  815. arrays.groups=dummy_groups<group_type,size_policy::min_size()>();
  816. }
  817. else{
  818. auto sal=storage_allocator(al);
  819. arrays.elements=boost::to_address(
  820. storage_traits::allocate(sal,buffer_size(groups_size)));
  821. /* Align arrays.groups to sizeof(group_type). table_iterator critically
  822. * depends on such alignment for its increment operation.
  823. */
  824. auto p=reinterpret_cast<unsigned char*>(arrays.elements+groups_size*N-1);
  825. p+=(uintptr_t(sizeof(group_type))-
  826. reinterpret_cast<uintptr_t>(p))%sizeof(group_type);
  827. arrays.groups=reinterpret_cast<group_type*>(p);
  828. /* memset is faster/not slower than initializing groups individually.
  829. * This assumes all zeros is group_type's default layout.
  830. */
  831. std::memset(arrays.groups,0,sizeof(group_type)*groups_size);
  832. arrays.groups[groups_size-1].set_sentinel();
  833. }
  834. return arrays;
  835. }
  836. template<typename Allocator>
  837. static void delete_(Allocator& al,table_arrays& arrays)noexcept
  838. {
  839. using storage_alloc=typename boost::allocator_rebind<Allocator,Value>::type;
  840. using storage_traits=boost::allocator_traits<storage_alloc>;
  841. using pointer=typename storage_traits::pointer;
  842. using pointer_traits=boost::pointer_traits<pointer>;
  843. auto sal=storage_alloc(al);
  844. if(arrays.elements){
  845. storage_traits::deallocate(
  846. sal,pointer_traits::pointer_to(*arrays.elements),
  847. buffer_size(arrays.groups_size_mask+1));
  848. }
  849. }
  850. /* combined space for elements and groups measured in sizeof(value_type)s */
  851. static std::size_t buffer_size(std::size_t groups_size)
  852. {
  853. auto buffer_bytes=
  854. /* space for elements (we subtract 1 because of the sentinel) */
  855. sizeof(value_type)*(groups_size*N-1)+
  856. /* space for groups + padding for group alignment */
  857. sizeof(group_type)*(groups_size+1)-1;
  858. /* ceil(buffer_bytes/sizeof(value_type)) */
  859. return (buffer_bytes+sizeof(value_type)-1)/sizeof(value_type);
  860. }
  861. std::size_t groups_size_index;
  862. std::size_t groups_size_mask;
  863. group_type *groups;
  864. value_type *elements;
  865. };
  866. struct if_constexpr_void_else{void operator()()const{}};
  867. template<bool B,typename F,typename G=if_constexpr_void_else>
  868. void if_constexpr(F f,G g={})
  869. {
  870. std::get<B?0:1>(std::forward_as_tuple(f,g))();
  871. }
  872. template<bool B,typename T,typename std::enable_if<B>::type* =nullptr>
  873. void copy_assign_if(T& x,const T& y){x=y;}
  874. template<bool B,typename T,typename std::enable_if<!B>::type* =nullptr>
  875. void copy_assign_if(T&,const T&){}
  876. template<bool B,typename T,typename std::enable_if<B>::type* =nullptr>
  877. void move_assign_if(T& x,T& y){x=std::move(y);}
  878. template<bool B,typename T,typename std::enable_if<!B>::type* =nullptr>
  879. void move_assign_if(T&,T&){}
  880. template<bool B,typename T,typename std::enable_if<B>::type* =nullptr>
  881. void swap_if(T& x,T& y){using std::swap; swap(x,y);}
  882. template<bool B,typename T,typename std::enable_if<!B>::type* =nullptr>
  883. void swap_if(T&,T&){}
  884. inline void prefetch(const void* p)
  885. {
  886. (void) p;
  887. #if defined(BOOST_GCC)||defined(BOOST_CLANG)
  888. __builtin_prefetch((const char*)p);
  889. #elif defined(BOOST_UNORDERED_SSE2)
  890. _mm_prefetch((const char*)p,_MM_HINT_T0);
  891. #endif
  892. }
  893. struct try_emplace_args_t{};
  894. template<typename Allocator>
  895. struct is_std_allocator:std::false_type{};
  896. template<typename T>
  897. struct is_std_allocator<std::allocator<T>>:std::true_type{};
  898. /* std::allocator::construct marked as deprecated */
  899. #if defined(_LIBCPP_SUPPRESS_DEPRECATED_PUSH)
  900. _LIBCPP_SUPPRESS_DEPRECATED_PUSH
  901. #elif defined(_STL_DISABLE_DEPRECATED_WARNING)
  902. _STL_DISABLE_DEPRECATED_WARNING
  903. #elif defined(_MSC_VER)
  904. #pragma warning(push)
  905. #pragma warning(disable:4996)
  906. #endif
  907. template<typename Allocator,typename Ptr,typename... Args>
  908. struct alloc_has_construct
  909. {
  910. private:
  911. template<typename Allocator2>
  912. static decltype(
  913. std::declval<Allocator2&>().construct(
  914. std::declval<Ptr>(),std::declval<Args&&>()...),
  915. std::true_type{}
  916. ) check(int);
  917. template<typename> static std::false_type check(...);
  918. public:
  919. static constexpr bool value=decltype(check<Allocator>(0))::value;
  920. };
  921. #if defined(_LIBCPP_SUPPRESS_DEPRECATED_POP)
  922. _LIBCPP_SUPPRESS_DEPRECATED_POP
  923. #elif defined(_STL_RESTORE_DEPRECATED_WARNING)
  924. _STL_RESTORE_DEPRECATED_WARNING
  925. #elif defined(_MSC_VER)
  926. #pragma warning(pop)
  927. #endif
  928. #if defined(BOOST_GCC)
  929. /* GCC's -Wshadow triggers at scenarios like this:
  930. *
  931. * struct foo{};
  932. * template<typename Base>
  933. * struct derived:Base
  934. * {
  935. * void f(){int foo;}
  936. * };
  937. *
  938. * derived<foo>x;
  939. * x.f(); // declaration of "foo" in derived::f shadows base type "foo"
  940. *
  941. * This makes shadowing warnings unavoidable in general when a class template
  942. * derives from user-provided classes, as is the case with table and
  943. * empty_value's below.
  944. */
  945. #pragma GCC diagnostic push
  946. #pragma GCC diagnostic ignored "-Wshadow"
  947. #endif
  948. #if defined(BOOST_MSVC)
  949. #pragma warning(push)
  950. #pragma warning(disable:4714) /* marked as __forceinline not inlined */
  951. #endif
  952. #if BOOST_WORKAROUND(BOOST_MSVC,<=1900)
  953. /* VS2015 marks as unreachable generic catch clauses around non-throwing
  954. * code.
  955. */
  956. #pragma warning(push)
  957. #pragma warning(disable:4702)
  958. #endif
  959. /* We expose the hard-coded max load factor so that tests can use it without
  960. * needing to pull it from an instantiated class template such as the table
  961. * class
  962. */
  963. constexpr static float const mlf = 0.875f;
  964. template <class T>
  965. union uninitialized_storage
  966. {
  967. T t_;
  968. uninitialized_storage(){}
  969. ~uninitialized_storage(){}
  970. };
  971. /* foa::table interface departs in a number of ways from that of C++ unordered
  972. * associative containers because it's not for end-user consumption
  973. * (boost::unordered_[flat|node]_[map|set]) wrappers complete it as
  974. * appropriate).
  975. *
  976. * The table supports two main modes of operation: node-based and flat. In the
  977. * node-based case, buckets store pointers to individually heap-allocated
  978. * elements. For flat, buckets directly store elements.
  979. *
  980. * For both tables:
  981. *
  982. * - begin() is not O(1).
  983. * - No bucket API.
  984. * - Load factor is fixed and can't be set by the user.
  985. *
  986. * For the inline table:
  987. *
  988. * - value_type must be moveable.
  989. * - Pointer stability is not kept under rehashing.
  990. * - No extract API.
  991. *
  992. * The TypePolicy template parameter is used to generate instantiations
  993. * suitable for either maps or sets, and introduces non-standard init_type:
  994. *
  995. * - TypePolicy::key_type and TypePolicy::value_type have the obvious
  996. * meaning.
  997. *
  998. * - TypePolicy::init_type is the type implicitly converted to when
  999. * writing x.insert({...}). For maps, this is std::pair<Key,T> rather
  1000. * than std::pair<const Key,T> so that, for instance, x.insert({"hello",0})
  1001. * produces a cheaply moveable std::string&& ("hello") rather than
  1002. * a copyable const std::string&&. foa::table::insert is extended to accept
  1003. * both init_type and value_type references.
  1004. *
  1005. * - TypePolicy::construct and TypePolicy::destroy are used for the
  1006. * construction and destruction of the internal types: value_type, init_type
  1007. * and element_type.
  1008. *
  1009. * - TypePolicy::move is used to provide move semantics for the internal
  1010. * types used by the container during rehashing and emplace. These types
  1011. * are init_type, value_type and emplace_type. During insertion, a
  1012. * stack-local type will be created based on the constructibility of the
  1013. * value_type and the supplied arguments. TypePolicy::move is used here
  1014. * for transfer of ownership. Similarly, TypePolicy::move is also used
  1015. * during rehashing when elements are moved to the new table.
  1016. *
  1017. * - TypePolicy::extract returns a const reference to the key part of
  1018. * a value of type value_type, init_type, element_type or
  1019. * decltype(TypePolicy::move(...)).
  1020. *
  1021. * - TypePolicy::element_type is the type that table_arrays uses when
  1022. * allocating buckets. For flat containers, this is value_type. For node
  1023. * containers, this is a strong typedef to value_type*.
  1024. *
  1025. * - TypePolicy::value_from returns a mutable reference to value_type from
  1026. * a given element_type. This is used when elements of the table themselves
  1027. * need to be moved, such as during move construction/assignment when
  1028. * allocators are unequal and there is no propagation. For all other cases,
  1029. * the element_type itself is moved.
  1030. *
  1031. * try_emplace, erase and find support heterogenous lookup by default, that is,
  1032. * without checking for any ::is_transparent typedefs --the checking is done by
  1033. * boost::unordered_[flat|node]_[map|set].
  1034. */
  1035. template<typename TypePolicy,typename Hash,typename Pred,typename Allocator>
  1036. class
  1037. #if defined(_MSC_VER)&&_MSC_FULL_VER>=190023918
  1038. __declspec(empty_bases) /* activate EBO with multiple inheritance */
  1039. #endif
  1040. table:empty_value<Hash,0>,empty_value<Pred,1>,empty_value<Allocator,2>
  1041. {
  1042. using hash_base=empty_value<Hash,0>;
  1043. using pred_base=empty_value<Pred,1>;
  1044. using allocator_base=empty_value<Allocator,2>;
  1045. using type_policy=TypePolicy;
  1046. using group_type=group15;
  1047. static constexpr auto N=group_type::N;
  1048. using size_policy=pow2_size_policy;
  1049. using prober=pow2_quadratic_prober;
  1050. using mix_policy=typename std::conditional<
  1051. hash_is_avalanching<Hash>::value,
  1052. no_mix,
  1053. mulx_mix
  1054. >::type;
  1055. using alloc_traits=boost::allocator_traits<Allocator>;
  1056. public:
  1057. using key_type=typename type_policy::key_type;
  1058. using init_type=typename type_policy::init_type;
  1059. using value_type=typename type_policy::value_type;
  1060. using element_type=typename type_policy::element_type;
  1061. private:
  1062. static constexpr bool has_mutable_iterator=
  1063. !std::is_same<key_type,value_type>::value;
  1064. public:
  1065. using hasher=Hash;
  1066. using key_equal=Pred;
  1067. using allocator_type=Allocator;
  1068. using pointer=value_type*;
  1069. using const_pointer=const value_type*;
  1070. using reference=value_type&;
  1071. using const_reference=const value_type&;
  1072. using size_type=std::size_t;
  1073. using difference_type=std::ptrdiff_t;
  1074. using const_iterator=table_iterator<type_policy,group_type,true>;
  1075. using iterator=typename std::conditional<
  1076. has_mutable_iterator,
  1077. table_iterator<type_policy,group_type,false>,
  1078. const_iterator>::type;
  1079. table(
  1080. std::size_t n=0,const Hash& h_=Hash(),const Pred& pred_=Pred(),
  1081. const Allocator& al_=Allocator()):
  1082. hash_base{empty_init,h_},pred_base{empty_init,pred_},
  1083. allocator_base{empty_init,al_},size_{0},arrays(new_arrays(n)),
  1084. ml{initial_max_load()}
  1085. {}
  1086. table(const table& x):
  1087. table{x,alloc_traits::select_on_container_copy_construction(x.al())}{}
  1088. table(table&& x)
  1089. noexcept(
  1090. std::is_nothrow_move_constructible<Hash>::value&&
  1091. std::is_nothrow_move_constructible<Pred>::value&&
  1092. std::is_nothrow_move_constructible<Allocator>::value):
  1093. hash_base{empty_init,std::move(x.h())},
  1094. pred_base{empty_init,std::move(x.pred())},
  1095. allocator_base{empty_init,std::move(x.al())},
  1096. size_{x.size_},arrays(x.arrays),ml{x.ml}
  1097. {
  1098. x.size_=0;
  1099. x.arrays=x.new_arrays(0);
  1100. x.ml=x.initial_max_load();
  1101. }
  1102. table(const table& x,const Allocator& al_):
  1103. table{std::size_t(std::ceil(float(x.size())/mlf)),x.h(),x.pred(),al_}
  1104. {
  1105. copy_elements_from(x);
  1106. }
  1107. table(table&& x,const Allocator& al_):
  1108. table{0,std::move(x.h()),std::move(x.pred()),al_}
  1109. {
  1110. if(al()==x.al()){
  1111. std::swap(size_,x.size_);
  1112. std::swap(arrays,x.arrays);
  1113. std::swap(ml,x.ml);
  1114. }
  1115. else{
  1116. reserve(x.size());
  1117. clear_on_exit c{x};
  1118. (void)c; /* unused var warning */
  1119. /* This works because subsequent x.clear() does not depend on the
  1120. * elements' values.
  1121. */
  1122. x.for_all_elements([this](element_type* p){
  1123. unchecked_insert(type_policy::move(type_policy::value_from(*p)));
  1124. });
  1125. }
  1126. }
  1127. ~table()noexcept
  1128. {
  1129. for_all_elements([this](element_type* p){
  1130. destroy_element(p);
  1131. });
  1132. delete_arrays(arrays);
  1133. }
  1134. table& operator=(const table& x)
  1135. {
  1136. BOOST_UNORDERED_STATIC_ASSERT_HASH_PRED(Hash, Pred)
  1137. static constexpr auto pocca=
  1138. alloc_traits::propagate_on_container_copy_assignment::value;
  1139. if(this!=std::addressof(x)){
  1140. // if copy construction here winds up throwing, the container is still
  1141. // left intact so we perform these operations first
  1142. hasher tmp_h=x.h();
  1143. key_equal tmp_p=x.pred();
  1144. // already noexcept, clear() before we swap the Hash, Pred just in case
  1145. // the clear() impl relies on them at some point in the future
  1146. clear();
  1147. // because we've asserted at compile-time that Hash and Pred are nothrow
  1148. // swappable, we can safely mutate our source container and maintain
  1149. // consistency between the Hash, Pred compatibility
  1150. using std::swap;
  1151. swap(h(),tmp_h);
  1152. swap(pred(),tmp_p);
  1153. if_constexpr<pocca>([&,this]{
  1154. if(al()!=x.al())reserve(0);
  1155. copy_assign_if<pocca>(al(),x.al());
  1156. });
  1157. /* noshrink: favor memory reuse over tightness */
  1158. noshrink_reserve(x.size());
  1159. copy_elements_from(x);
  1160. }
  1161. return *this;
  1162. }
  1163. #if defined(BOOST_MSVC)
  1164. #pragma warning(push)
  1165. #pragma warning(disable:4127) /* conditional expression is constant */
  1166. #endif
  1167. table& operator=(table&& x)
  1168. noexcept(
  1169. alloc_traits::propagate_on_container_move_assignment::value||
  1170. alloc_traits::is_always_equal::value)
  1171. {
  1172. BOOST_UNORDERED_STATIC_ASSERT_HASH_PRED(Hash, Pred)
  1173. static constexpr auto pocma=
  1174. alloc_traits::propagate_on_container_move_assignment::value;
  1175. if(this!=std::addressof(x)){
  1176. /* Given ambiguity in implementation strategies briefly discussed here:
  1177. * https://www.open-std.org/jtc1/sc22/wg21/docs/lwg-active.html#2227
  1178. *
  1179. * we opt into requiring nothrow swappability and eschew the move
  1180. * operations associated with Hash, Pred.
  1181. *
  1182. * To this end, we ensure that the user never has to consider the
  1183. * moved-from state of their Hash, Pred objects
  1184. */
  1185. using std::swap;
  1186. clear();
  1187. swap(h(),x.h());
  1188. swap(pred(),x.pred());
  1189. if(pocma||al()==x.al()){
  1190. reserve(0);
  1191. move_assign_if<pocma>(al(),x.al());
  1192. swap(size_,x.size_);
  1193. swap(arrays,x.arrays);
  1194. swap(ml,x.ml);
  1195. }
  1196. else{
  1197. /* noshrink: favor memory reuse over tightness */
  1198. noshrink_reserve(x.size());
  1199. clear_on_exit c{x};
  1200. (void)c; /* unused var warning */
  1201. /* This works because subsequent x.clear() does not depend on the
  1202. * elements' values.
  1203. */
  1204. x.for_all_elements([this](element_type* p){
  1205. unchecked_insert(type_policy::move(type_policy::value_from(*p)));
  1206. });
  1207. }
  1208. }
  1209. return *this;
  1210. }
  1211. #if defined(BOOST_MSVC)
  1212. #pragma warning(pop) /* C4127 */
  1213. #endif
  1214. allocator_type get_allocator()const noexcept{return al();}
  1215. iterator begin()noexcept
  1216. {
  1217. iterator it{arrays.groups,0,arrays.elements};
  1218. if(!(arrays.groups[0].match_occupied()&0x1))++it;
  1219. return it;
  1220. }
  1221. const_iterator begin()const noexcept
  1222. {return const_cast<table*>(this)->begin();}
  1223. iterator end()noexcept{return {};}
  1224. const_iterator end()const noexcept{return const_cast<table*>(this)->end();}
  1225. const_iterator cbegin()const noexcept{return begin();}
  1226. const_iterator cend()const noexcept{return end();}
  1227. bool empty()const noexcept{return size()==0;}
  1228. std::size_t size()const noexcept{return size_;}
  1229. std::size_t max_size()const noexcept{return SIZE_MAX;}
  1230. template<typename... Args>
  1231. BOOST_FORCEINLINE std::pair<iterator,bool> emplace(Args&&... args)
  1232. {
  1233. using emplace_type=typename std::conditional<
  1234. std::is_constructible<init_type,Args...>::value,
  1235. init_type,
  1236. value_type
  1237. >::type;
  1238. using insert_type=typename std::conditional<
  1239. std::is_constructible<
  1240. value_type,emplace_type>::value,
  1241. emplace_type,element_type
  1242. >::type;
  1243. uninitialized_storage<insert_type> s;
  1244. auto *p=std::addressof(s.t_);
  1245. type_policy::construct(al(),p,std::forward<Args>(args)...);
  1246. destroy_on_exit<insert_type> guard{al(),p};
  1247. return emplace_impl(type_policy::move(*p));
  1248. }
  1249. template<typename Key,typename... Args>
  1250. BOOST_FORCEINLINE std::pair<iterator,bool> try_emplace(
  1251. Key&& x,Args&&... args)
  1252. {
  1253. return emplace_impl(
  1254. try_emplace_args_t{},std::forward<Key>(x),std::forward<Args>(args)...);
  1255. }
  1256. BOOST_FORCEINLINE std::pair<iterator,bool>
  1257. insert(const init_type& x){return emplace_impl(x);}
  1258. BOOST_FORCEINLINE std::pair<iterator,bool>
  1259. insert(init_type&& x){return emplace_impl(std::move(x));}
  1260. /* template<typename=void> tilts call ambiguities in favor of init_type */
  1261. template<typename=void>
  1262. BOOST_FORCEINLINE std::pair<iterator,bool>
  1263. insert(const value_type& x){return emplace_impl(x);}
  1264. template<typename=void>
  1265. BOOST_FORCEINLINE std::pair<iterator,bool>
  1266. insert(value_type&& x){return emplace_impl(std::move(x));}
  1267. template<typename T=element_type>
  1268. BOOST_FORCEINLINE
  1269. typename std::enable_if<
  1270. !std::is_same<T,value_type>::value,
  1271. std::pair<iterator,bool>
  1272. >::type
  1273. insert(element_type&& x){return emplace_impl(std::move(x));}
  1274. template<
  1275. bool dependent_value=false,
  1276. typename std::enable_if<
  1277. has_mutable_iterator||dependent_value>::type* =nullptr
  1278. >
  1279. void erase(iterator pos)noexcept{return erase(const_iterator(pos));}
  1280. BOOST_FORCEINLINE
  1281. void erase(const_iterator pos)noexcept
  1282. {
  1283. destroy_element(pos.p);
  1284. recover_slot(pos.pc);
  1285. }
  1286. template<typename Key>
  1287. BOOST_FORCEINLINE
  1288. auto erase(Key&& x) -> typename std::enable_if<
  1289. !std::is_convertible<Key,iterator>::value&&
  1290. !std::is_convertible<Key,const_iterator>::value, std::size_t>::type
  1291. {
  1292. auto it=find(x);
  1293. if(it!=end()){
  1294. erase(it);
  1295. return 1;
  1296. }
  1297. else return 0;
  1298. }
  1299. void swap(table& x)
  1300. noexcept(
  1301. alloc_traits::propagate_on_container_swap::value||
  1302. alloc_traits::is_always_equal::value)
  1303. {
  1304. BOOST_UNORDERED_STATIC_ASSERT_HASH_PRED(Hash, Pred)
  1305. static constexpr auto pocs=
  1306. alloc_traits::propagate_on_container_swap::value;
  1307. using std::swap;
  1308. if_constexpr<pocs>([&,this]{
  1309. swap_if<pocs>(al(),x.al());
  1310. },
  1311. [&,this]{ /* else */
  1312. BOOST_ASSERT(al()==x.al());
  1313. (void)this; /* makes sure captured this is used */
  1314. });
  1315. swap(h(),x.h());
  1316. swap(pred(),x.pred());
  1317. swap(size_,x.size_);
  1318. swap(arrays,x.arrays);
  1319. swap(ml,x.ml);
  1320. }
  1321. void clear()noexcept
  1322. {
  1323. auto p=arrays.elements;
  1324. if(p){
  1325. for(auto pg=arrays.groups,last=pg+arrays.groups_size_mask+1;
  1326. pg!=last;++pg,p+=N){
  1327. auto mask=pg->match_really_occupied();
  1328. while(mask){
  1329. destroy_element(p+unchecked_countr_zero(mask));
  1330. mask&=mask-1;
  1331. }
  1332. /* we wipe the entire metadata to reset the overflow byte as well */
  1333. pg->initialize();
  1334. }
  1335. arrays.groups[arrays.groups_size_mask].set_sentinel();
  1336. size_=0;
  1337. ml=initial_max_load();
  1338. }
  1339. }
  1340. element_type extract(const_iterator pos)
  1341. {
  1342. BOOST_ASSERT(pos!=end());
  1343. erase_on_exit e{*this,pos};
  1344. (void)e;
  1345. return std::move(*pos.p);
  1346. }
  1347. // TODO: should we accept different allocator too?
  1348. template<typename Hash2,typename Pred2>
  1349. void merge(table<TypePolicy,Hash2,Pred2,Allocator>& x)
  1350. {
  1351. x.for_all_elements([&,this](group_type* pg,unsigned int n,element_type* p){
  1352. erase_on_exit e{x,{pg,n,p}};
  1353. if(!emplace_impl(type_policy::move(*p)).second)e.rollback();
  1354. });
  1355. }
  1356. template<typename Hash2,typename Pred2>
  1357. void merge(table<TypePolicy,Hash2,Pred2,Allocator>&& x){merge(x);}
  1358. hasher hash_function()const{return h();}
  1359. key_equal key_eq()const{return pred();}
  1360. template<typename Key>
  1361. BOOST_FORCEINLINE iterator find(const Key& x)
  1362. {
  1363. auto hash=hash_for(x);
  1364. return find_impl(x,position_for(hash),hash);
  1365. }
  1366. template<typename Key>
  1367. BOOST_FORCEINLINE const_iterator find(const Key& x)const
  1368. {
  1369. return const_cast<table*>(this)->find(x);
  1370. }
  1371. std::size_t capacity()const noexcept
  1372. {
  1373. return arrays.elements?(arrays.groups_size_mask+1)*N-1:0;
  1374. }
  1375. float load_factor()const noexcept
  1376. {
  1377. if (capacity() == 0) { return 0; }
  1378. return float(size())/float(capacity());
  1379. }
  1380. float max_load_factor()const noexcept{return mlf;}
  1381. std::size_t max_load()const noexcept{return ml;}
  1382. void rehash(std::size_t n)
  1383. {
  1384. auto m=size_t(std::ceil(float(size())/mlf));
  1385. if(m>n)n=m;
  1386. if(n)n=capacity_for(n); /* exact resulting capacity */
  1387. if(n!=capacity())unchecked_rehash(n);
  1388. }
  1389. void reserve(std::size_t n)
  1390. {
  1391. rehash(std::size_t(std::ceil(float(n)/mlf)));
  1392. }
  1393. template<typename Predicate>
  1394. friend std::size_t erase_if(table& x,Predicate pr)
  1395. {
  1396. return x.erase_if_impl(pr);
  1397. }
  1398. private:
  1399. template<typename,typename,typename,typename> friend class table;
  1400. using arrays_type=table_arrays<element_type,group_type,size_policy>;
  1401. struct clear_on_exit
  1402. {
  1403. ~clear_on_exit(){x.clear();}
  1404. table& x;
  1405. };
  1406. struct erase_on_exit
  1407. {
  1408. erase_on_exit(table& x_,const_iterator it_):x{x_},it{it_}{}
  1409. ~erase_on_exit(){if(!rollback_)x.erase(it);}
  1410. void rollback(){rollback_=true;}
  1411. table& x;
  1412. const_iterator it;
  1413. bool rollback_=false;
  1414. };
  1415. template <class T>
  1416. struct destroy_on_exit
  1417. {
  1418. Allocator &a;
  1419. T *p;
  1420. ~destroy_on_exit(){type_policy::destroy(a,p);};
  1421. };
  1422. Hash& h(){return hash_base::get();}
  1423. const Hash& h()const{return hash_base::get();}
  1424. Pred& pred(){return pred_base::get();}
  1425. const Pred& pred()const{return pred_base::get();}
  1426. Allocator& al(){return allocator_base::get();}
  1427. const Allocator& al()const{return allocator_base::get();}
  1428. arrays_type new_arrays(std::size_t n)
  1429. {
  1430. return arrays_type::new_(al(),n);
  1431. }
  1432. void delete_arrays(arrays_type& arrays_)noexcept
  1433. {
  1434. arrays_type::delete_(al(),arrays_);
  1435. }
  1436. template<typename... Args>
  1437. void construct_element(element_type* p,Args&&... args)
  1438. {
  1439. type_policy::construct(al(),p,std::forward<Args>(args)...);
  1440. }
  1441. template<typename... Args>
  1442. void construct_element(element_type* p,try_emplace_args_t,Args&&... args)
  1443. {
  1444. construct_element_from_try_emplace_args(
  1445. p,
  1446. std::integral_constant<bool,std::is_same<key_type,value_type>::value>{},
  1447. std::forward<Args>(args)...);
  1448. }
  1449. template<typename Key,typename... Args>
  1450. void construct_element_from_try_emplace_args(
  1451. element_type* p,std::false_type,Key&& x,Args&&... args)
  1452. {
  1453. type_policy::construct(
  1454. al(),p,
  1455. std::piecewise_construct,
  1456. std::forward_as_tuple(std::forward<Key>(x)),
  1457. std::forward_as_tuple(std::forward<Args>(args)...));
  1458. }
  1459. /* This overload allows boost::unordered_flat_set to internally use
  1460. * try_emplace to implement heterogeneous insert (P2363).
  1461. */
  1462. template<typename Key>
  1463. void construct_element_from_try_emplace_args(
  1464. element_type* p,std::true_type,Key&& x)
  1465. {
  1466. type_policy::construct(al(),p,std::forward<Key>(x));
  1467. }
  1468. void destroy_element(element_type* p)noexcept
  1469. {
  1470. type_policy::destroy(al(),p);
  1471. }
  1472. struct destroy_element_on_exit
  1473. {
  1474. ~destroy_element_on_exit(){this_->destroy_element(p);}
  1475. table *this_;
  1476. element_type *p;
  1477. };
  1478. void copy_elements_from(const table& x)
  1479. {
  1480. BOOST_ASSERT(empty());
  1481. BOOST_ASSERT(this!=std::addressof(x));
  1482. if(arrays.groups_size_mask==x.arrays.groups_size_mask){
  1483. fast_copy_elements_from(x);
  1484. }
  1485. else{
  1486. x.for_all_elements([this](const element_type* p){
  1487. unchecked_insert(*p);
  1488. });
  1489. }
  1490. }
  1491. void fast_copy_elements_from(const table& x)
  1492. {
  1493. if(arrays.elements){
  1494. copy_elements_array_from(x);
  1495. std::memcpy(
  1496. arrays.groups,x.arrays.groups,
  1497. (arrays.groups_size_mask+1)*sizeof(group_type));
  1498. size_=x.size();
  1499. }
  1500. }
  1501. void copy_elements_array_from(const table& x)
  1502. {
  1503. copy_elements_array_from(
  1504. x,
  1505. std::integral_constant<
  1506. bool,
  1507. #if BOOST_WORKAROUND(BOOST_LIBSTDCXX_VERSION,<50000)
  1508. /* std::is_trivially_copy_constructible not provided */
  1509. boost::has_trivial_copy<element_type>::value
  1510. #else
  1511. std::is_trivially_copy_constructible<element_type>::value
  1512. #endif
  1513. &&(
  1514. is_std_allocator<Allocator>::value||
  1515. !alloc_has_construct<Allocator,value_type*,const value_type&>::value)
  1516. >{}
  1517. );
  1518. }
  1519. void copy_elements_array_from(const table& x,std::true_type /* -> memcpy */)
  1520. {
  1521. /* reinterpret_cast: GCC may complain about value_type not being trivially
  1522. * copy-assignable when we're relying on trivial copy constructibility.
  1523. */
  1524. std::memcpy(
  1525. reinterpret_cast<unsigned char*>(arrays.elements),
  1526. reinterpret_cast<unsigned char*>(x.arrays.elements),
  1527. x.capacity()*sizeof(value_type));
  1528. }
  1529. void copy_elements_array_from(const table& x,std::false_type /* -> manual */)
  1530. {
  1531. std::size_t num_constructed=0;
  1532. BOOST_TRY{
  1533. x.for_all_elements([&,this](const element_type* p){
  1534. construct_element(arrays.elements+(p-x.arrays.elements),*p);
  1535. ++num_constructed;
  1536. });
  1537. }
  1538. BOOST_CATCH(...){
  1539. if(num_constructed){
  1540. x.for_all_elements_while([&,this](const element_type* p){
  1541. destroy_element(arrays.elements+(p-x.arrays.elements));
  1542. return --num_constructed!=0;
  1543. });
  1544. }
  1545. BOOST_RETHROW
  1546. }
  1547. BOOST_CATCH_END
  1548. }
  1549. void recover_slot(unsigned char* pc)
  1550. {
  1551. /* If this slot potentially caused overflow, we decrease the maximum load so
  1552. * that average probe length won't increase unboundedly in repeated
  1553. * insert/erase cycles (drift).
  1554. */
  1555. ml-=group_type::maybe_caused_overflow(pc);
  1556. group_type::reset(pc);
  1557. --size_;
  1558. }
  1559. void recover_slot(group_type* pg,std::size_t pos)
  1560. {
  1561. recover_slot(reinterpret_cast<unsigned char*>(pg)+pos);
  1562. }
  1563. std::size_t initial_max_load()const
  1564. {
  1565. static constexpr std::size_t small_capacity=2*N-1;
  1566. auto capacity_=capacity();
  1567. if(capacity_<=small_capacity){
  1568. return capacity_; /* we allow 100% usage */
  1569. }
  1570. else{
  1571. return (std::size_t)(mlf*(float)(capacity_));
  1572. }
  1573. }
  1574. template<typename T>
  1575. static inline auto key_from(const T& x)
  1576. ->decltype(type_policy::extract(x))
  1577. {
  1578. return type_policy::extract(x);
  1579. }
  1580. template<typename Key,typename... Args>
  1581. static inline const Key& key_from(
  1582. try_emplace_args_t,const Key& x,const Args&...)
  1583. {
  1584. return x;
  1585. }
  1586. template<typename Key>
  1587. inline std::size_t hash_for(const Key& x)const
  1588. {
  1589. return mix_policy::mix(h(),x);
  1590. }
  1591. inline std::size_t position_for(std::size_t hash)const
  1592. {
  1593. return position_for(hash,arrays);
  1594. }
  1595. static inline std::size_t position_for(
  1596. std::size_t hash,const arrays_type& arrays_)
  1597. {
  1598. return size_policy::position(hash,arrays_.groups_size_index);
  1599. }
  1600. static inline void prefetch_elements(const element_type* p)
  1601. {
  1602. /* We have experimentally confirmed that ARM architectures get a higher
  1603. * speedup when around the first half of the element slots in a group are
  1604. * prefetched, whereas for Intel just the first cache line is best.
  1605. * Please report back if you find better tunings for some particular
  1606. * architectures.
  1607. */
  1608. #if BOOST_ARCH_ARM
  1609. /* Cache line size can't be known at compile time, so we settle on
  1610. * the very frequent value of 64B.
  1611. */
  1612. constexpr int cache_line=64;
  1613. const char *p0=reinterpret_cast<const char*>(p),
  1614. *p1=p0+sizeof(value_type)*N/2;
  1615. for(;p0<p1;p0+=cache_line)prefetch(p0);
  1616. #else
  1617. prefetch(p);
  1618. #endif
  1619. }
  1620. #if defined(BOOST_MSVC)
  1621. /* warning: forcing value to bool 'true' or 'false' in bool(pred()...) */
  1622. #pragma warning(push)
  1623. #pragma warning(disable:4800)
  1624. #endif
  1625. template<typename Key>
  1626. BOOST_FORCEINLINE iterator find_impl(
  1627. const Key& x,std::size_t pos0,std::size_t hash)const
  1628. {
  1629. prober pb(pos0);
  1630. do{
  1631. auto pos=pb.get();
  1632. auto pg=arrays.groups+pos;
  1633. auto mask=pg->match(hash);
  1634. if(mask){
  1635. BOOST_UNORDERED_ASSUME(arrays.elements != nullptr);
  1636. auto p=arrays.elements+pos*N;
  1637. prefetch_elements(p);
  1638. do{
  1639. auto n=unchecked_countr_zero(mask);
  1640. if(BOOST_LIKELY(bool(pred()(x,key_from(p[n]))))){
  1641. return {pg,n,p+n};
  1642. }
  1643. mask&=mask-1;
  1644. }while(mask);
  1645. }
  1646. if(BOOST_LIKELY(pg->is_not_overflowed(hash))){
  1647. return {}; /* end() */
  1648. }
  1649. }
  1650. while(BOOST_LIKELY(pb.next(arrays.groups_size_mask)));
  1651. return {}; /* end() */
  1652. }
  1653. #if defined(BOOST_MSVC)
  1654. #pragma warning(pop) /* C4800 */
  1655. #endif
  1656. template<typename... Args>
  1657. BOOST_FORCEINLINE std::pair<iterator,bool> emplace_impl(Args&&... args)
  1658. {
  1659. const auto &k=key_from(std::forward<Args>(args)...);
  1660. auto hash=hash_for(k);
  1661. auto pos0=position_for(hash);
  1662. auto it=find_impl(k,pos0,hash);
  1663. if(it!=end()){
  1664. return {it,false};
  1665. }
  1666. if(BOOST_LIKELY(size_<ml)){
  1667. return {
  1668. unchecked_emplace_at(pos0,hash,std::forward<Args>(args)...),
  1669. true
  1670. };
  1671. }
  1672. else{
  1673. return {
  1674. unchecked_emplace_with_rehash(hash,std::forward<Args>(args)...),
  1675. true
  1676. };
  1677. }
  1678. }
  1679. static std::size_t capacity_for(std::size_t n)
  1680. {
  1681. return size_policy::size(size_index_for<group_type,size_policy>(n))*N-1;
  1682. }
  1683. template<typename... Args>
  1684. BOOST_NOINLINE iterator
  1685. unchecked_emplace_with_rehash(std::size_t hash,Args&&... args)
  1686. {
  1687. /* Due to the anti-drift mechanism (see recover_slot), new_arrays_ may be
  1688. * of the same size as the old arrays; in the limit, erasing one element at
  1689. * full load and then inserting could bring us back to the same capacity
  1690. * after a costly rehash. To avoid this, we jump to the next capacity level
  1691. * when the number of erased elements is <= 10% of total elements at full
  1692. * load, which is implemented by requesting additional F*size elements,
  1693. * with F = P * 10% / (1 - P * 10%), where P is the probability of an
  1694. * element having caused overflow; P has been measured as ~0.162 under
  1695. * ideal conditions, yielding F ~ 0.0165 ~ 1/61.
  1696. */
  1697. auto new_arrays_=new_arrays(std::size_t(
  1698. std::ceil(static_cast<float>(size_+size_/61+1)/mlf)));
  1699. iterator it;
  1700. BOOST_TRY{
  1701. /* strong exception guarantee -> try insertion before rehash */
  1702. it=nosize_unchecked_emplace_at(
  1703. new_arrays_,position_for(hash,new_arrays_),
  1704. hash,std::forward<Args>(args)...);
  1705. }
  1706. BOOST_CATCH(...){
  1707. delete_arrays(new_arrays_);
  1708. BOOST_RETHROW
  1709. }
  1710. BOOST_CATCH_END
  1711. /* new_arrays_ lifetime taken care of by unchecked_rehash */
  1712. unchecked_rehash(new_arrays_);
  1713. ++size_;
  1714. return it;
  1715. }
  1716. BOOST_NOINLINE void unchecked_rehash(std::size_t n)
  1717. {
  1718. auto new_arrays_=new_arrays(n);
  1719. unchecked_rehash(new_arrays_);
  1720. }
  1721. BOOST_NOINLINE void unchecked_rehash(arrays_type& new_arrays_)
  1722. {
  1723. std::size_t num_destroyed=0;
  1724. BOOST_TRY{
  1725. for_all_elements([&,this](element_type* p){
  1726. nosize_transfer_element(p,new_arrays_,num_destroyed);
  1727. });
  1728. }
  1729. BOOST_CATCH(...){
  1730. if(num_destroyed){
  1731. for_all_elements_while(
  1732. [&,this](group_type* pg,unsigned int n,element_type*){
  1733. recover_slot(pg,n);
  1734. return --num_destroyed!=0;
  1735. }
  1736. );
  1737. }
  1738. for_all_elements(new_arrays_,[this](element_type* p){
  1739. destroy_element(p);
  1740. });
  1741. delete_arrays(new_arrays_);
  1742. BOOST_RETHROW
  1743. }
  1744. BOOST_CATCH_END
  1745. /* either all moved and destroyed or all copied */
  1746. BOOST_ASSERT(num_destroyed==size()||num_destroyed==0);
  1747. if(num_destroyed!=size()){
  1748. for_all_elements([this](element_type* p){
  1749. destroy_element(p);
  1750. });
  1751. }
  1752. delete_arrays(arrays);
  1753. arrays=new_arrays_;
  1754. ml=initial_max_load();
  1755. }
  1756. void noshrink_reserve(std::size_t n)
  1757. {
  1758. /* used only on assignment after element clearance */
  1759. BOOST_ASSERT(empty());
  1760. if(n){
  1761. n=std::size_t(std::ceil(float(n)/mlf)); /* elements -> slots */
  1762. n=capacity_for(n); /* exact resulting capacity */
  1763. if(n>capacity()){
  1764. auto new_arrays_=new_arrays(n);
  1765. delete_arrays(arrays);
  1766. arrays=new_arrays_;
  1767. ml=initial_max_load();
  1768. }
  1769. }
  1770. }
  1771. template<typename Value>
  1772. void unchecked_insert(Value&& x)
  1773. {
  1774. auto hash=hash_for(key_from(x));
  1775. unchecked_emplace_at(position_for(hash),hash,std::forward<Value>(x));
  1776. }
  1777. void nosize_transfer_element(
  1778. element_type* p,const arrays_type& arrays_,std::size_t& num_destroyed)
  1779. {
  1780. nosize_transfer_element(
  1781. p,hash_for(key_from(*p)),arrays_,num_destroyed,
  1782. std::integral_constant< /* std::move_if_noexcept semantics */
  1783. bool,
  1784. std::is_nothrow_move_constructible<init_type>::value||
  1785. !std::is_same<element_type,value_type>::value||
  1786. !std::is_copy_constructible<element_type>::value>{});
  1787. }
  1788. void nosize_transfer_element(
  1789. element_type* p,std::size_t hash,const arrays_type& arrays_,
  1790. std::size_t& num_destroyed,std::true_type /* ->move */)
  1791. {
  1792. /* Destroy p even if an an exception is thrown in the middle of move
  1793. * construction, which could leave the source half-moved.
  1794. */
  1795. ++num_destroyed;
  1796. destroy_element_on_exit d{this,p};
  1797. (void)d; /* unused var warning */
  1798. nosize_unchecked_emplace_at(
  1799. arrays_,position_for(hash,arrays_),hash,type_policy::move(*p));
  1800. }
  1801. void nosize_transfer_element(
  1802. element_type* p,std::size_t hash,const arrays_type& arrays_,
  1803. std::size_t& /*num_destroyed*/,std::false_type /* ->copy */)
  1804. {
  1805. nosize_unchecked_emplace_at(
  1806. arrays_,position_for(hash,arrays_),hash,
  1807. const_cast<const element_type&>(*p));
  1808. }
  1809. template<typename... Args>
  1810. iterator unchecked_emplace_at(
  1811. std::size_t pos0,std::size_t hash,Args&&... args)
  1812. {
  1813. auto res=nosize_unchecked_emplace_at(
  1814. arrays,pos0,hash,std::forward<Args>(args)...);
  1815. ++size_;
  1816. return res;
  1817. }
  1818. template<typename... Args>
  1819. iterator nosize_unchecked_emplace_at(
  1820. const arrays_type& arrays_,std::size_t pos0,std::size_t hash,
  1821. Args&&... args)
  1822. {
  1823. for(prober pb(pos0);;pb.next(arrays_.groups_size_mask)){
  1824. auto pos=pb.get();
  1825. auto pg=arrays_.groups+pos;
  1826. auto mask=pg->match_available();
  1827. if(BOOST_LIKELY(mask!=0)){
  1828. auto n=unchecked_countr_zero(mask);
  1829. auto p=arrays_.elements+pos*N+n;
  1830. construct_element(p,std::forward<Args>(args)...);
  1831. pg->set(n,hash);
  1832. return {pg,n,p};
  1833. }
  1834. else pg->mark_overflow(hash);
  1835. }
  1836. }
  1837. template<typename Predicate>
  1838. std::size_t erase_if_impl(Predicate pr)
  1839. {
  1840. std::size_t s=size();
  1841. for_all_elements([&,this](group_type* pg,unsigned int n,element_type* p){
  1842. if(pr(type_policy::value_from(*p))) erase(iterator{pg,n,p});
  1843. });
  1844. return std::size_t(s-size());
  1845. }
  1846. template<typename F>
  1847. void for_all_elements(F f)const
  1848. {
  1849. for_all_elements(arrays,f);
  1850. }
  1851. template<typename F>
  1852. static auto for_all_elements(const arrays_type& arrays_,F f)
  1853. ->decltype(f(nullptr),void())
  1854. {
  1855. for_all_elements_while(arrays_,[&](element_type* p){f(p);return true;});
  1856. }
  1857. template<typename F>
  1858. static auto for_all_elements(const arrays_type& arrays_,F f)
  1859. ->decltype(f(nullptr,0,nullptr),void())
  1860. {
  1861. for_all_elements_while(
  1862. arrays_,[&](group_type* pg,unsigned int n,element_type* p)
  1863. {f(pg,n,p);return true;});
  1864. }
  1865. template<typename F>
  1866. void for_all_elements_while(F f)const
  1867. {
  1868. for_all_elements_while(arrays,f);
  1869. }
  1870. template<typename F>
  1871. static auto for_all_elements_while(const arrays_type& arrays_,F f)
  1872. ->decltype(f(nullptr),void())
  1873. {
  1874. for_all_elements_while(
  1875. arrays_,[&](group_type*,unsigned int,element_type* p){return f(p);});
  1876. }
  1877. template<typename F>
  1878. static auto for_all_elements_while(const arrays_type& arrays_,F f)
  1879. ->decltype(f(nullptr,0,nullptr),void())
  1880. {
  1881. auto p=arrays_.elements;
  1882. if(!p){return;}
  1883. for(auto pg=arrays_.groups,last=pg+arrays_.groups_size_mask+1;
  1884. pg!=last;++pg,p+=N){
  1885. auto mask=pg->match_really_occupied();
  1886. while(mask){
  1887. auto n=unchecked_countr_zero(mask);
  1888. if(!f(pg,n,p+n))return;
  1889. mask&=mask-1;
  1890. }
  1891. }
  1892. }
  1893. std::size_t size_;
  1894. arrays_type arrays;
  1895. std::size_t ml;
  1896. };
  1897. #if BOOST_WORKAROUND(BOOST_MSVC,<=1900)
  1898. #pragma warning(pop) /* C4702 */
  1899. #endif
  1900. #if defined(BOOST_MSVC)
  1901. #pragma warning(pop) /* C4714 */
  1902. #endif
  1903. #if defined(BOOST_GCC)
  1904. #pragma GCC diagnostic pop /* ignored "-Wshadow" */
  1905. #endif
  1906. } /* namespace foa */
  1907. } /* namespace detail */
  1908. } /* namespace unordered */
  1909. } /* namespace boost */
  1910. #undef BOOST_UNORDERED_STATIC_ASSERT_HASH_PRED
  1911. #undef BOOST_UNORDERED_ASSUME
  1912. #undef BOOST_UNORDERED_HAS_BUILTIN
  1913. #endif