robin_hood.hpp 92 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537
  1. // Fast & memory efficient hashtable based on robin hood hashing for C++11/14/17/20
  2. // https://github.com/martinus/robin-hood-hashing
  3. //
  4. // Licensed under the MIT License <http://opensource.org/licenses/MIT>.
  5. // SPDX-License-Identifier: MIT
  6. // Copyright (c) 2018-2021 Martin Ankerl <http://martin.ankerl.com>
  7. //
  8. // Permission is hereby granted, free of charge, to any person obtaining a copy
  9. // of this software and associated documentation files (the "Software"), to deal
  10. // in the Software without restriction, including without limitation the rights
  11. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12. // copies of the Software, and to permit persons to whom the Software is
  13. // furnished to do so, subject to the following conditions:
  14. //
  15. // The above copyright notice and this permission notice shall be included in all
  16. // copies or substantial portions of the Software.
  17. //
  18. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  21. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  24. // SOFTWARE.
  25. #ifndef ROBIN_HOOD_H_INCLUDED
  26. #define ROBIN_HOOD_H_INCLUDED
  27. // see https://semver.org/
  28. #define ROBIN_HOOD_VERSION_MAJOR 3 // for incompatible API changes
  29. #define ROBIN_HOOD_VERSION_MINOR 11 // for adding functionality in a backwards-compatible manner
  30. #define ROBIN_HOOD_VERSION_PATCH 5 // for backwards-compatible bug fixes
  31. #include <algorithm>
  32. #include <cstdlib>
  33. #include <cstring>
  34. #include <functional>
  35. #include <limits>
  36. #include <memory> // only to support hash of smart pointers
  37. #include <stdexcept>
  38. #include <string>
  39. #include <type_traits>
  40. #include <utility>
  41. #if __cplusplus >= 201703L
  42. # include <string_view>
  43. #endif
  44. // #define ROBIN_HOOD_LOG_ENABLED
  45. #ifdef ROBIN_HOOD_LOG_ENABLED
  46. # include <iostream>
  47. # define ROBIN_HOOD_LOG(...) \
  48. std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << __VA_ARGS__ << std::endl;
  49. #else
  50. # define ROBIN_HOOD_LOG(x)
  51. #endif
  52. // #define ROBIN_HOOD_TRACE_ENABLED
  53. #ifdef ROBIN_HOOD_TRACE_ENABLED
  54. # include <iostream>
  55. # define ROBIN_HOOD_TRACE(...) \
  56. std::cout << __FUNCTION__ << "@" << __LINE__ << ": " << __VA_ARGS__ << std::endl;
  57. #else
  58. # define ROBIN_HOOD_TRACE(x)
  59. #endif
  60. // #define ROBIN_HOOD_COUNT_ENABLED
  61. #ifdef ROBIN_HOOD_COUNT_ENABLED
  62. # include <iostream>
  63. # define ROBIN_HOOD_COUNT(x) ++counts().x;
  64. namespace robin_hood {
  65. struct Counts {
  66. uint64_t shiftUp{};
  67. uint64_t shiftDown{};
  68. };
  69. inline std::ostream& operator<<(std::ostream& os, Counts const& c) {
  70. return os << c.shiftUp << " shiftUp" << std::endl << c.shiftDown << " shiftDown" << std::endl;
  71. }
  72. static Counts& counts() {
  73. static Counts counts{};
  74. return counts;
  75. }
  76. } // namespace robin_hood
  77. #else
  78. # define ROBIN_HOOD_COUNT(x)
  79. #endif
  80. // all non-argument macros should use this facility. See
  81. // https://www.fluentcpp.com/2019/05/28/better-macros-better-flags/
  82. #define ROBIN_HOOD(x) ROBIN_HOOD_PRIVATE_DEFINITION_##x()
  83. // mark unused members with this macro
  84. #define ROBIN_HOOD_UNUSED(identifier)
  85. // bitness
  86. #if SIZE_MAX == UINT32_MAX
  87. # define ROBIN_HOOD_PRIVATE_DEFINITION_BITNESS() 32
  88. #elif SIZE_MAX == UINT64_MAX
  89. # define ROBIN_HOOD_PRIVATE_DEFINITION_BITNESS() 64
  90. #else
  91. # error Unsupported bitness
  92. #endif
  93. // endianess
  94. #ifdef _MSC_VER
  95. # define ROBIN_HOOD_PRIVATE_DEFINITION_LITTLE_ENDIAN() 1
  96. # define ROBIN_HOOD_PRIVATE_DEFINITION_BIG_ENDIAN() 0
  97. #else
  98. # define ROBIN_HOOD_PRIVATE_DEFINITION_LITTLE_ENDIAN() \
  99. (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
  100. # define ROBIN_HOOD_PRIVATE_DEFINITION_BIG_ENDIAN() (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
  101. #endif
  102. // inline
  103. #ifdef _MSC_VER
  104. # define ROBIN_HOOD_PRIVATE_DEFINITION_NOINLINE() __declspec(noinline)
  105. #else
  106. # define ROBIN_HOOD_PRIVATE_DEFINITION_NOINLINE() __attribute__((noinline))
  107. #endif
  108. // exceptions
  109. #if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND)
  110. # define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_EXCEPTIONS() 0
  111. #else
  112. # define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_EXCEPTIONS() 1
  113. #endif
  114. // count leading/trailing bits
  115. #if !defined(ROBIN_HOOD_DISABLE_INTRINSICS)
  116. # ifdef _MSC_VER
  117. # if ROBIN_HOOD(BITNESS) == 32
  118. # define ROBIN_HOOD_PRIVATE_DEFINITION_BITSCANFORWARD() _BitScanForward
  119. # else
  120. # define ROBIN_HOOD_PRIVATE_DEFINITION_BITSCANFORWARD() _BitScanForward64
  121. # endif
  122. # include <intrin.h>
  123. # pragma intrinsic(ROBIN_HOOD(BITSCANFORWARD))
  124. # define ROBIN_HOOD_COUNT_TRAILING_ZEROES(x) \
  125. [](size_t mask) noexcept -> int { \
  126. unsigned long index; \
  127. return ROBIN_HOOD(BITSCANFORWARD)(&index, mask) ? static_cast<int>(index) \
  128. : ROBIN_HOOD(BITNESS); \
  129. }(x)
  130. # else
  131. # if ROBIN_HOOD(BITNESS) == 32
  132. # define ROBIN_HOOD_PRIVATE_DEFINITION_CTZ() __builtin_ctzl
  133. # define ROBIN_HOOD_PRIVATE_DEFINITION_CLZ() __builtin_clzl
  134. # else
  135. # define ROBIN_HOOD_PRIVATE_DEFINITION_CTZ() __builtin_ctzll
  136. # define ROBIN_HOOD_PRIVATE_DEFINITION_CLZ() __builtin_clzll
  137. # endif
  138. # define ROBIN_HOOD_COUNT_LEADING_ZEROES(x) ((x) ? ROBIN_HOOD(CLZ)(x) : ROBIN_HOOD(BITNESS))
  139. # define ROBIN_HOOD_COUNT_TRAILING_ZEROES(x) ((x) ? ROBIN_HOOD(CTZ)(x) : ROBIN_HOOD(BITNESS))
  140. # endif
  141. #endif
  142. // fallthrough
  143. #ifndef __has_cpp_attribute // For backwards compatibility
  144. # define __has_cpp_attribute(x) 0
  145. #endif
  146. #if __has_cpp_attribute(clang::fallthrough)
  147. # define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH() [[clang::fallthrough]]
  148. #elif __has_cpp_attribute(gnu::fallthrough)
  149. # define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH() [[gnu::fallthrough]]
  150. #else
  151. # define ROBIN_HOOD_PRIVATE_DEFINITION_FALLTHROUGH()
  152. #endif
  153. // likely/unlikely
  154. #ifdef _MSC_VER
  155. # define ROBIN_HOOD_LIKELY(condition) condition
  156. # define ROBIN_HOOD_UNLIKELY(condition) condition
  157. #else
  158. # define ROBIN_HOOD_LIKELY(condition) __builtin_expect(condition, 1)
  159. # define ROBIN_HOOD_UNLIKELY(condition) __builtin_expect(condition, 0)
  160. #endif
  161. // detect if native wchar_t type is availiable in MSVC
  162. #ifdef _MSC_VER
  163. # ifdef _NATIVE_WCHAR_T_DEFINED
  164. # define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 1
  165. # else
  166. # define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 0
  167. # endif
  168. #else
  169. # define ROBIN_HOOD_PRIVATE_DEFINITION_HAS_NATIVE_WCHART() 1
  170. #endif
  171. // detect if MSVC supports the pair(std::piecewise_construct_t,...) consructor being constexpr
  172. #ifdef _MSC_VER
  173. # if _MSC_VER <= 1900
  174. # define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 1
  175. # else
  176. # define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 0
  177. # endif
  178. #else
  179. # define ROBIN_HOOD_PRIVATE_DEFINITION_BROKEN_CONSTEXPR() 0
  180. #endif
  181. // workaround missing "is_trivially_copyable" in g++ < 5.0
  182. // See https://stackoverflow.com/a/31798726/48181
  183. #if defined(__GNUC__) && __GNUC__ < 5
  184. # define ROBIN_HOOD_IS_TRIVIALLY_COPYABLE(...) __has_trivial_copy(__VA_ARGS__)
  185. #else
  186. # define ROBIN_HOOD_IS_TRIVIALLY_COPYABLE(...) std::is_trivially_copyable<__VA_ARGS__>::value
  187. #endif
  188. // helpers for C++ versions, see https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
  189. #define ROBIN_HOOD_PRIVATE_DEFINITION_CXX() __cplusplus
  190. #define ROBIN_HOOD_PRIVATE_DEFINITION_CXX98() 199711L
  191. #define ROBIN_HOOD_PRIVATE_DEFINITION_CXX11() 201103L
  192. #define ROBIN_HOOD_PRIVATE_DEFINITION_CXX14() 201402L
  193. #define ROBIN_HOOD_PRIVATE_DEFINITION_CXX17() 201703L
  194. #if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX17)
  195. # define ROBIN_HOOD_PRIVATE_DEFINITION_NODISCARD() [[nodiscard]]
  196. #else
  197. # define ROBIN_HOOD_PRIVATE_DEFINITION_NODISCARD()
  198. #endif
  199. namespace robin_hood {
  200. #if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX14)
  201. # define ROBIN_HOOD_STD std
  202. #else
  203. // c++11 compatibility layer
  204. namespace ROBIN_HOOD_STD {
  205. template <class T>
  206. struct alignment_of
  207. : std::integral_constant<std::size_t, alignof(typename std::remove_all_extents<T>::type)> {};
  208. template <class T, T... Ints>
  209. class integer_sequence {
  210. public:
  211. using value_type = T;
  212. static_assert(std::is_integral<value_type>::value, "not integral type");
  213. static constexpr std::size_t size() noexcept {
  214. return sizeof...(Ints);
  215. }
  216. };
  217. template <std::size_t... Inds>
  218. using index_sequence = integer_sequence<std::size_t, Inds...>;
  219. namespace detail_ {
  220. template <class T, T Begin, T End, bool>
  221. struct IntSeqImpl {
  222. using TValue = T;
  223. static_assert(std::is_integral<TValue>::value, "not integral type");
  224. static_assert(Begin >= 0 && Begin < End, "unexpected argument (Begin<0 || Begin<=End)");
  225. template <class, class>
  226. struct IntSeqCombiner;
  227. template <TValue... Inds0, TValue... Inds1>
  228. struct IntSeqCombiner<integer_sequence<TValue, Inds0...>, integer_sequence<TValue, Inds1...>> {
  229. using TResult = integer_sequence<TValue, Inds0..., Inds1...>;
  230. };
  231. using TResult =
  232. typename IntSeqCombiner<typename IntSeqImpl<TValue, Begin, Begin + (End - Begin) / 2,
  233. (End - Begin) / 2 == 1>::TResult,
  234. typename IntSeqImpl<TValue, Begin + (End - Begin) / 2, End,
  235. (End - Begin + 1) / 2 == 1>::TResult>::TResult;
  236. };
  237. template <class T, T Begin>
  238. struct IntSeqImpl<T, Begin, Begin, false> {
  239. using TValue = T;
  240. static_assert(std::is_integral<TValue>::value, "not integral type");
  241. static_assert(Begin >= 0, "unexpected argument (Begin<0)");
  242. using TResult = integer_sequence<TValue>;
  243. };
  244. template <class T, T Begin, T End>
  245. struct IntSeqImpl<T, Begin, End, true> {
  246. using TValue = T;
  247. static_assert(std::is_integral<TValue>::value, "not integral type");
  248. static_assert(Begin >= 0, "unexpected argument (Begin<0)");
  249. using TResult = integer_sequence<TValue, Begin>;
  250. };
  251. } // namespace detail_
  252. template <class T, T N>
  253. using make_integer_sequence = typename detail_::IntSeqImpl<T, 0, N, (N - 0) == 1>::TResult;
  254. template <std::size_t N>
  255. using make_index_sequence = make_integer_sequence<std::size_t, N>;
  256. template <class... T>
  257. using index_sequence_for = make_index_sequence<sizeof...(T)>;
  258. } // namespace ROBIN_HOOD_STD
  259. #endif
  260. namespace detail {
  261. // make sure we static_cast to the correct type for hash_int
  262. #if ROBIN_HOOD(BITNESS) == 64
  263. using SizeT = uint64_t;
  264. #else
  265. using SizeT = uint32_t;
  266. #endif
  267. template <typename T>
  268. T rotr(T x, unsigned k) {
  269. return (x >> k) | (x << (8U * sizeof(T) - k));
  270. }
  271. // This cast gets rid of warnings like "cast from 'uint8_t*' {aka 'unsigned char*'} to
  272. // 'uint64_t*' {aka 'long unsigned int*'} increases required alignment of target type". Use with
  273. // care!
  274. template <typename T>
  275. inline T reinterpret_cast_no_cast_align_warning(void* ptr) noexcept {
  276. return reinterpret_cast<T>(ptr);
  277. }
  278. template <typename T>
  279. inline T reinterpret_cast_no_cast_align_warning(void const* ptr) noexcept {
  280. return reinterpret_cast<T>(ptr);
  281. }
  282. // make sure this is not inlined as it is slow and dramatically enlarges code, thus making other
  283. // inlinings more difficult. Throws are also generally the slow path.
  284. template <typename E, typename... Args>
  285. [[noreturn]] ROBIN_HOOD(NOINLINE)
  286. #if ROBIN_HOOD(HAS_EXCEPTIONS)
  287. void doThrow(Args&&... args) {
  288. // NOLINTNEXTLINE(cppcoreguidelines-pro-bounds-array-to-pointer-decay)
  289. throw E(std::forward<Args>(args)...);
  290. }
  291. #else
  292. void doThrow(Args&&... ROBIN_HOOD_UNUSED(args) /*unused*/) {
  293. abort();
  294. }
  295. #endif
  296. template <typename E, typename T, typename... Args>
  297. T* assertNotNull(T* t, Args&&... args) {
  298. if (ROBIN_HOOD_UNLIKELY(nullptr == t)) {
  299. doThrow<E>(std::forward<Args>(args)...);
  300. }
  301. return t;
  302. }
  303. template <typename T>
  304. inline T unaligned_load(void const* ptr) noexcept {
  305. // using memcpy so we don't get into unaligned load problems.
  306. // compiler should optimize this very well anyways.
  307. T t;
  308. std::memcpy(&t, ptr, sizeof(T));
  309. return t;
  310. }
  311. // Allocates bulks of memory for objects of type T. This deallocates the memory in the destructor,
  312. // and keeps a linked list of the allocated memory around. Overhead per allocation is the size of a
  313. // pointer.
  314. template <typename T, size_t MinNumAllocs = 4, size_t MaxNumAllocs = 256>
  315. class BulkPoolAllocator {
  316. public:
  317. BulkPoolAllocator() noexcept = default;
  318. // does not copy anything, just creates a new allocator.
  319. BulkPoolAllocator(const BulkPoolAllocator& ROBIN_HOOD_UNUSED(o) /*unused*/) noexcept
  320. : mHead(nullptr)
  321. , mListForFree(nullptr) {}
  322. BulkPoolAllocator(BulkPoolAllocator&& o) noexcept
  323. : mHead(o.mHead)
  324. , mListForFree(o.mListForFree) {
  325. o.mListForFree = nullptr;
  326. o.mHead = nullptr;
  327. }
  328. BulkPoolAllocator& operator=(BulkPoolAllocator&& o) noexcept {
  329. reset();
  330. mHead = o.mHead;
  331. mListForFree = o.mListForFree;
  332. o.mListForFree = nullptr;
  333. o.mHead = nullptr;
  334. return *this;
  335. }
  336. BulkPoolAllocator&
  337. // NOLINTNEXTLINE(bugprone-unhandled-self-assignment,cert-oop54-cpp)
  338. operator=(const BulkPoolAllocator& ROBIN_HOOD_UNUSED(o) /*unused*/) noexcept {
  339. // does not do anything
  340. return *this;
  341. }
  342. ~BulkPoolAllocator() noexcept {
  343. reset();
  344. }
  345. // Deallocates all allocated memory.
  346. void reset() noexcept {
  347. while (mListForFree) {
  348. T* tmp = *mListForFree;
  349. ROBIN_HOOD_LOG("std::free")
  350. std::free(mListForFree);
  351. mListForFree = reinterpret_cast_no_cast_align_warning<T**>(tmp);
  352. }
  353. mHead = nullptr;
  354. }
  355. // allocates, but does NOT initialize. Use in-place new constructor, e.g.
  356. // T* obj = pool.allocate();
  357. // ::new (static_cast<void*>(obj)) T();
  358. T* allocate() {
  359. T* tmp = mHead;
  360. if (!tmp) {
  361. tmp = performAllocation();
  362. }
  363. mHead = *reinterpret_cast_no_cast_align_warning<T**>(tmp);
  364. return tmp;
  365. }
  366. // does not actually deallocate but puts it in store.
  367. // make sure you have already called the destructor! e.g. with
  368. // obj->~T();
  369. // pool.deallocate(obj);
  370. void deallocate(T* obj) noexcept {
  371. *reinterpret_cast_no_cast_align_warning<T**>(obj) = mHead;
  372. mHead = obj;
  373. }
  374. // Adds an already allocated block of memory to the allocator. This allocator is from now on
  375. // responsible for freeing the data (with free()). If the provided data is not large enough to
  376. // make use of, it is immediately freed. Otherwise it is reused and freed in the destructor.
  377. void addOrFree(void* ptr, const size_t numBytes) noexcept {
  378. // calculate number of available elements in ptr
  379. if (numBytes < ALIGNMENT + ALIGNED_SIZE) {
  380. // not enough data for at least one element. Free and return.
  381. ROBIN_HOOD_LOG("std::free")
  382. std::free(ptr);
  383. } else {
  384. ROBIN_HOOD_LOG("add to buffer")
  385. add(ptr, numBytes);
  386. }
  387. }
  388. void swap(BulkPoolAllocator<T, MinNumAllocs, MaxNumAllocs>& other) noexcept {
  389. using std::swap;
  390. swap(mHead, other.mHead);
  391. swap(mListForFree, other.mListForFree);
  392. }
  393. private:
  394. // iterates the list of allocated memory to calculate how many to alloc next.
  395. // Recalculating this each time saves us a size_t member.
  396. // This ignores the fact that memory blocks might have been added manually with addOrFree. In
  397. // practice, this should not matter much.
  398. ROBIN_HOOD(NODISCARD) size_t calcNumElementsToAlloc() const noexcept {
  399. auto tmp = mListForFree;
  400. size_t numAllocs = MinNumAllocs;
  401. while (numAllocs * 2 <= MaxNumAllocs && tmp) {
  402. auto x = reinterpret_cast<T***>(tmp);
  403. tmp = *x;
  404. numAllocs *= 2;
  405. }
  406. return numAllocs;
  407. }
  408. // WARNING: Underflow if numBytes < ALIGNMENT! This is guarded in addOrFree().
  409. void add(void* ptr, const size_t numBytes) noexcept {
  410. const size_t numElements = (numBytes - ALIGNMENT) / ALIGNED_SIZE;
  411. auto data = reinterpret_cast<T**>(ptr);
  412. // link free list
  413. auto x = reinterpret_cast<T***>(data);
  414. *x = mListForFree;
  415. mListForFree = data;
  416. // create linked list for newly allocated data
  417. auto* const headT =
  418. reinterpret_cast_no_cast_align_warning<T*>(reinterpret_cast<char*>(ptr) + ALIGNMENT);
  419. auto* const head = reinterpret_cast<char*>(headT);
  420. // Visual Studio compiler automatically unrolls this loop, which is pretty cool
  421. for (size_t i = 0; i < numElements; ++i) {
  422. *reinterpret_cast_no_cast_align_warning<char**>(head + i * ALIGNED_SIZE) =
  423. head + (i + 1) * ALIGNED_SIZE;
  424. }
  425. // last one points to 0
  426. *reinterpret_cast_no_cast_align_warning<T**>(head + (numElements - 1) * ALIGNED_SIZE) =
  427. mHead;
  428. mHead = headT;
  429. }
  430. // Called when no memory is available (mHead == 0).
  431. // Don't inline this slow path.
  432. ROBIN_HOOD(NOINLINE) T* performAllocation() {
  433. size_t const numElementsToAlloc = calcNumElementsToAlloc();
  434. // alloc new memory: [prev |T, T, ... T]
  435. size_t const bytes = ALIGNMENT + ALIGNED_SIZE * numElementsToAlloc;
  436. ROBIN_HOOD_LOG("std::malloc " << bytes << " = " << ALIGNMENT << " + " << ALIGNED_SIZE
  437. << " * " << numElementsToAlloc)
  438. add(assertNotNull<std::bad_alloc>(std::malloc(bytes)), bytes);
  439. return mHead;
  440. }
  441. // enforce byte alignment of the T's
  442. #if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX14)
  443. static constexpr size_t ALIGNMENT =
  444. (std::max)(std::alignment_of<T>::value, std::alignment_of<T*>::value);
  445. #else
  446. static const size_t ALIGNMENT =
  447. (ROBIN_HOOD_STD::alignment_of<T>::value > ROBIN_HOOD_STD::alignment_of<T*>::value)
  448. ? ROBIN_HOOD_STD::alignment_of<T>::value
  449. : +ROBIN_HOOD_STD::alignment_of<T*>::value; // the + is for walkarround
  450. #endif
  451. static constexpr size_t ALIGNED_SIZE = ((sizeof(T) - 1) / ALIGNMENT + 1) * ALIGNMENT;
  452. static_assert(MinNumAllocs >= 1, "MinNumAllocs");
  453. static_assert(MaxNumAllocs >= MinNumAllocs, "MaxNumAllocs");
  454. static_assert(ALIGNED_SIZE >= sizeof(T*), "ALIGNED_SIZE");
  455. static_assert(0 == (ALIGNED_SIZE % sizeof(T*)), "ALIGNED_SIZE mod");
  456. static_assert(ALIGNMENT >= sizeof(T*), "ALIGNMENT");
  457. T* mHead{nullptr};
  458. T** mListForFree{nullptr};
  459. };
  460. template <typename T, size_t MinSize, size_t MaxSize, bool IsFlat>
  461. struct NodeAllocator;
  462. // dummy allocator that does nothing
  463. template <typename T, size_t MinSize, size_t MaxSize>
  464. struct NodeAllocator<T, MinSize, MaxSize, true> {
  465. // we are not using the data, so just free it.
  466. void addOrFree(void* ptr, size_t ROBIN_HOOD_UNUSED(numBytes) /*unused*/) noexcept {
  467. ROBIN_HOOD_LOG("std::free")
  468. std::free(ptr);
  469. }
  470. };
  471. template <typename T, size_t MinSize, size_t MaxSize>
  472. struct NodeAllocator<T, MinSize, MaxSize, false> : public BulkPoolAllocator<T, MinSize, MaxSize> {};
  473. // c++14 doesn't have is_nothrow_swappable, and clang++ 6.0.1 doesn't like it either, so I'm making
  474. // my own here.
  475. namespace swappable {
  476. #if ROBIN_HOOD(CXX) < ROBIN_HOOD(CXX17)
  477. using std::swap;
  478. template <typename T>
  479. struct nothrow {
  480. static const bool value = noexcept(swap(std::declval<T&>(), std::declval<T&>()));
  481. };
  482. #else
  483. template <typename T>
  484. struct nothrow {
  485. static const bool value = std::is_nothrow_swappable<T>::value;
  486. };
  487. #endif
  488. } // namespace swappable
  489. } // namespace detail
  490. struct is_transparent_tag {};
  491. // A custom pair implementation is used in the map because std::pair is not is_trivially_copyable,
  492. // which means it would not be allowed to be used in std::memcpy. This struct is copyable, which is
  493. // also tested.
  494. template <typename T1, typename T2>
  495. struct pair {
  496. using first_type = T1;
  497. using second_type = T2;
  498. template <typename U1 = T1, typename U2 = T2,
  499. typename = typename std::enable_if<std::is_default_constructible<U1>::value &&
  500. std::is_default_constructible<U2>::value>::type>
  501. constexpr pair() noexcept(noexcept(U1()) && noexcept(U2()))
  502. : first()
  503. , second() {}
  504. // pair constructors are explicit so we don't accidentally call this ctor when we don't have to.
  505. explicit constexpr pair(std::pair<T1, T2> const& o) noexcept(
  506. noexcept(T1(std::declval<T1 const&>())) && noexcept(T2(std::declval<T2 const&>())))
  507. : first(o.first)
  508. , second(o.second) {}
  509. // pair constructors are explicit so we don't accidentally call this ctor when we don't have to.
  510. explicit constexpr pair(std::pair<T1, T2>&& o) noexcept(noexcept(
  511. T1(std::move(std::declval<T1&&>()))) && noexcept(T2(std::move(std::declval<T2&&>()))))
  512. : first(std::move(o.first))
  513. , second(std::move(o.second)) {}
  514. constexpr pair(T1&& a, T2&& b) noexcept(noexcept(
  515. T1(std::move(std::declval<T1&&>()))) && noexcept(T2(std::move(std::declval<T2&&>()))))
  516. : first(std::move(a))
  517. , second(std::move(b)) {}
  518. template <typename U1, typename U2>
  519. constexpr pair(U1&& a, U2&& b) noexcept(noexcept(T1(std::forward<U1>(
  520. std::declval<U1&&>()))) && noexcept(T2(std::forward<U2>(std::declval<U2&&>()))))
  521. : first(std::forward<U1>(a))
  522. , second(std::forward<U2>(b)) {}
  523. template <typename... U1, typename... U2>
  524. // MSVC 2015 produces error "C2476: ‘constexpr’ constructor does not initialize all members"
  525. // if this constructor is constexpr
  526. #if !ROBIN_HOOD(BROKEN_CONSTEXPR)
  527. constexpr
  528. #endif
  529. pair(std::piecewise_construct_t /*unused*/, std::tuple<U1...> a,
  530. std::tuple<U2...>
  531. b) noexcept(noexcept(pair(std::declval<std::tuple<U1...>&>(),
  532. std::declval<std::tuple<U2...>&>(),
  533. ROBIN_HOOD_STD::index_sequence_for<U1...>(),
  534. ROBIN_HOOD_STD::index_sequence_for<U2...>())))
  535. : pair(a, b, ROBIN_HOOD_STD::index_sequence_for<U1...>(),
  536. ROBIN_HOOD_STD::index_sequence_for<U2...>()) {
  537. }
  538. // constructor called from the std::piecewise_construct_t ctor
  539. template <typename... U1, size_t... I1, typename... U2, size_t... I2>
  540. pair(std::tuple<U1...>& a, std::tuple<U2...>& b, ROBIN_HOOD_STD::index_sequence<I1...> /*unused*/, ROBIN_HOOD_STD::index_sequence<I2...> /*unused*/) noexcept(
  541. noexcept(T1(std::forward<U1>(std::get<I1>(
  542. std::declval<std::tuple<
  543. U1...>&>()))...)) && noexcept(T2(std::
  544. forward<U2>(std::get<I2>(
  545. std::declval<std::tuple<U2...>&>()))...)))
  546. : first(std::forward<U1>(std::get<I1>(a))...)
  547. , second(std::forward<U2>(std::get<I2>(b))...) {
  548. // make visual studio compiler happy about warning about unused a & b.
  549. // Visual studio's pair implementation disables warning 4100.
  550. (void)a;
  551. (void)b;
  552. }
  553. void swap(pair<T1, T2>& o) noexcept((detail::swappable::nothrow<T1>::value) &&
  554. (detail::swappable::nothrow<T2>::value)) {
  555. using std::swap;
  556. swap(first, o.first);
  557. swap(second, o.second);
  558. }
  559. T1 first; // NOLINT(misc-non-private-member-variables-in-classes)
  560. T2 second; // NOLINT(misc-non-private-member-variables-in-classes)
  561. };
  562. template <typename A, typename B>
  563. inline void swap(pair<A, B>& a, pair<A, B>& b) noexcept(
  564. noexcept(std::declval<pair<A, B>&>().swap(std::declval<pair<A, B>&>()))) {
  565. a.swap(b);
  566. }
  567. template <typename A, typename B>
  568. inline constexpr bool operator==(pair<A, B> const& x, pair<A, B> const& y) {
  569. return (x.first == y.first) && (x.second == y.second);
  570. }
  571. template <typename A, typename B>
  572. inline constexpr bool operator!=(pair<A, B> const& x, pair<A, B> const& y) {
  573. return !(x == y);
  574. }
  575. template <typename A, typename B>
  576. inline constexpr bool operator<(pair<A, B> const& x, pair<A, B> const& y) noexcept(noexcept(
  577. std::declval<A const&>() < std::declval<A const&>()) && noexcept(std::declval<B const&>() <
  578. std::declval<B const&>())) {
  579. return x.first < y.first || (!(y.first < x.first) && x.second < y.second);
  580. }
  581. template <typename A, typename B>
  582. inline constexpr bool operator>(pair<A, B> const& x, pair<A, B> const& y) {
  583. return y < x;
  584. }
  585. template <typename A, typename B>
  586. inline constexpr bool operator<=(pair<A, B> const& x, pair<A, B> const& y) {
  587. return !(x > y);
  588. }
  589. template <typename A, typename B>
  590. inline constexpr bool operator>=(pair<A, B> const& x, pair<A, B> const& y) {
  591. return !(x < y);
  592. }
  593. inline size_t hash_bytes(void const* ptr, size_t len) noexcept {
  594. static constexpr uint64_t m = UINT64_C(0xc6a4a7935bd1e995);
  595. static constexpr uint64_t seed = UINT64_C(0xe17a1465);
  596. static constexpr unsigned int r = 47;
  597. auto const* const data64 = static_cast<uint64_t const*>(ptr);
  598. uint64_t h = seed ^ (len * m);
  599. size_t const n_blocks = len / 8;
  600. for (size_t i = 0; i < n_blocks; ++i) {
  601. auto k = detail::unaligned_load<uint64_t>(data64 + i);
  602. k *= m;
  603. k ^= k >> r;
  604. k *= m;
  605. h ^= k;
  606. h *= m;
  607. }
  608. auto const* const data8 = reinterpret_cast<uint8_t const*>(data64 + n_blocks);
  609. switch (len & 7U) {
  610. case 7:
  611. h ^= static_cast<uint64_t>(data8[6]) << 48U;
  612. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  613. case 6:
  614. h ^= static_cast<uint64_t>(data8[5]) << 40U;
  615. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  616. case 5:
  617. h ^= static_cast<uint64_t>(data8[4]) << 32U;
  618. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  619. case 4:
  620. h ^= static_cast<uint64_t>(data8[3]) << 24U;
  621. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  622. case 3:
  623. h ^= static_cast<uint64_t>(data8[2]) << 16U;
  624. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  625. case 2:
  626. h ^= static_cast<uint64_t>(data8[1]) << 8U;
  627. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  628. case 1:
  629. h ^= static_cast<uint64_t>(data8[0]);
  630. h *= m;
  631. ROBIN_HOOD(FALLTHROUGH); // FALLTHROUGH
  632. default:
  633. break;
  634. }
  635. h ^= h >> r;
  636. // not doing the final step here, because this will be done by keyToIdx anyways
  637. // h *= m;
  638. // h ^= h >> r;
  639. return static_cast<size_t>(h);
  640. }
  641. inline size_t hash_int(uint64_t x) noexcept {
  642. // tried lots of different hashes, let's stick with murmurhash3. It's simple, fast, well tested,
  643. // and doesn't need any special 128bit operations.
  644. x ^= x >> 33U;
  645. x *= UINT64_C(0xff51afd7ed558ccd);
  646. x ^= x >> 33U;
  647. // not doing the final step here, because this will be done by keyToIdx anyways
  648. // x *= UINT64_C(0xc4ceb9fe1a85ec53);
  649. // x ^= x >> 33U;
  650. return static_cast<size_t>(x);
  651. }
  652. // A thin wrapper around std::hash, performing an additional simple mixing step of the result.
  653. template <typename T, typename Enable = void>
  654. struct hash : public std::hash<T> {
  655. size_t operator()(T const& obj) const
  656. noexcept(noexcept(std::declval<std::hash<T>>().operator()(std::declval<T const&>()))) {
  657. // call base hash
  658. auto result = std::hash<T>::operator()(obj);
  659. // return mixed of that, to be save against identity has
  660. return hash_int(static_cast<detail::SizeT>(result));
  661. }
  662. };
  663. template <typename CharT>
  664. struct hash<std::basic_string<CharT>> {
  665. size_t operator()(std::basic_string<CharT> const& str) const noexcept {
  666. return hash_bytes(str.data(), sizeof(CharT) * str.size());
  667. }
  668. };
  669. #if ROBIN_HOOD(CXX) >= ROBIN_HOOD(CXX17)
  670. template <typename CharT>
  671. struct hash<std::basic_string_view<CharT>> {
  672. size_t operator()(std::basic_string_view<CharT> const& sv) const noexcept {
  673. return hash_bytes(sv.data(), sizeof(CharT) * sv.size());
  674. }
  675. };
  676. #endif
  677. template <class T>
  678. struct hash<T*> {
  679. size_t operator()(T* ptr) const noexcept {
  680. return hash_int(reinterpret_cast<detail::SizeT>(ptr));
  681. }
  682. };
  683. template <class T>
  684. struct hash<std::unique_ptr<T>> {
  685. size_t operator()(std::unique_ptr<T> const& ptr) const noexcept {
  686. return hash_int(reinterpret_cast<detail::SizeT>(ptr.get()));
  687. }
  688. };
  689. template <class T>
  690. struct hash<std::shared_ptr<T>> {
  691. size_t operator()(std::shared_ptr<T> const& ptr) const noexcept {
  692. return hash_int(reinterpret_cast<detail::SizeT>(ptr.get()));
  693. }
  694. };
  695. template <typename Enum>
  696. struct hash<Enum, typename std::enable_if<std::is_enum<Enum>::value>::type> {
  697. size_t operator()(Enum e) const noexcept {
  698. using Underlying = typename std::underlying_type<Enum>::type;
  699. return hash<Underlying>{}(static_cast<Underlying>(e));
  700. }
  701. };
  702. #define ROBIN_HOOD_HASH_INT(T) \
  703. template <> \
  704. struct hash<T> { \
  705. size_t operator()(T const& obj) const noexcept { \
  706. return hash_int(static_cast<uint64_t>(obj)); \
  707. } \
  708. }
  709. #if defined(__GNUC__) && !defined(__clang__)
  710. # pragma GCC diagnostic push
  711. # pragma GCC diagnostic ignored "-Wuseless-cast"
  712. #endif
  713. // see https://en.cppreference.com/w/cpp/utility/hash
  714. ROBIN_HOOD_HASH_INT(bool);
  715. ROBIN_HOOD_HASH_INT(char);
  716. ROBIN_HOOD_HASH_INT(signed char);
  717. ROBIN_HOOD_HASH_INT(unsigned char);
  718. ROBIN_HOOD_HASH_INT(char16_t);
  719. ROBIN_HOOD_HASH_INT(char32_t);
  720. #if ROBIN_HOOD(HAS_NATIVE_WCHART)
  721. ROBIN_HOOD_HASH_INT(wchar_t);
  722. #endif
  723. ROBIN_HOOD_HASH_INT(short);
  724. ROBIN_HOOD_HASH_INT(unsigned short);
  725. ROBIN_HOOD_HASH_INT(int);
  726. ROBIN_HOOD_HASH_INT(unsigned int);
  727. ROBIN_HOOD_HASH_INT(long);
  728. ROBIN_HOOD_HASH_INT(long long);
  729. ROBIN_HOOD_HASH_INT(unsigned long);
  730. ROBIN_HOOD_HASH_INT(unsigned long long);
  731. #if defined(__GNUC__) && !defined(__clang__)
  732. # pragma GCC diagnostic pop
  733. #endif
  734. namespace detail {
  735. template <typename T>
  736. struct void_type {
  737. using type = void;
  738. };
  739. template <typename T, typename = void>
  740. struct has_is_transparent : public std::false_type {};
  741. template <typename T>
  742. struct has_is_transparent<T, typename void_type<typename T::is_transparent>::type>
  743. : public std::true_type {};
  744. // using wrapper classes for hash and key_equal prevents the diamond problem when the same type
  745. // is used. see https://stackoverflow.com/a/28771920/48181
  746. template <typename T>
  747. struct WrapHash : public T {
  748. WrapHash() = default;
  749. explicit WrapHash(T const& o) noexcept(noexcept(T(std::declval<T const&>())))
  750. : T(o) {}
  751. };
  752. template <typename T>
  753. struct WrapKeyEqual : public T {
  754. WrapKeyEqual() = default;
  755. explicit WrapKeyEqual(T const& o) noexcept(noexcept(T(std::declval<T const&>())))
  756. : T(o) {}
  757. };
  758. // A highly optimized hashmap implementation, using the Robin Hood algorithm.
  759. //
  760. // In most cases, this map should be usable as a drop-in replacement for std::unordered_map, but
  761. // be about 2x faster in most cases and require much less allocations.
  762. //
  763. // This implementation uses the following memory layout:
  764. //
  765. // [Node, Node, ... Node | info, info, ... infoSentinel ]
  766. //
  767. // * Node: either a DataNode that directly has the std::pair<key, val> as member,
  768. // or a DataNode with a pointer to std::pair<key,val>. Which DataNode representation to use
  769. // depends on how fast the swap() operation is. Heuristically, this is automatically choosen
  770. // based on sizeof(). there are always 2^n Nodes.
  771. //
  772. // * info: Each Node in the map has a corresponding info byte, so there are 2^n info bytes.
  773. // Each byte is initialized to 0, meaning the corresponding Node is empty. Set to 1 means the
  774. // corresponding node contains data. Set to 2 means the corresponding Node is filled, but it
  775. // actually belongs to the previous position and was pushed out because that place is already
  776. // taken.
  777. //
  778. // * infoSentinel: Sentinel byte set to 1, so that iterator's ++ can stop at end() without the
  779. // need for a idx variable.
  780. //
  781. // According to STL, order of templates has effect on throughput. That's why I've moved the
  782. // boolean to the front.
  783. // https://www.reddit.com/r/cpp/comments/ahp6iu/compile_time_binary_size_reductions_and_cs_future/eeguck4/
  784. template <bool IsFlat, size_t MaxLoadFactor100, typename Key, typename T, typename Hash,
  785. typename KeyEqual>
  786. class Table
  787. : public WrapHash<Hash>,
  788. public WrapKeyEqual<KeyEqual>,
  789. detail::NodeAllocator<
  790. typename std::conditional<
  791. std::is_void<T>::value, Key,
  792. robin_hood::pair<typename std::conditional<IsFlat, Key, Key const>::type, T>>::type,
  793. 4, 16384, IsFlat> {
  794. public:
  795. static constexpr bool is_flat = IsFlat;
  796. static constexpr bool is_map = !std::is_void<T>::value;
  797. static constexpr bool is_set = !is_map;
  798. static constexpr bool is_transparent =
  799. has_is_transparent<Hash>::value && has_is_transparent<KeyEqual>::value;
  800. using key_type = Key;
  801. using mapped_type = T;
  802. using value_type = typename std::conditional<
  803. is_set, Key,
  804. robin_hood::pair<typename std::conditional<is_flat, Key, Key const>::type, T>>::type;
  805. using size_type = size_t;
  806. using hasher = Hash;
  807. using key_equal = KeyEqual;
  808. using Self = Table<IsFlat, MaxLoadFactor100, key_type, mapped_type, hasher, key_equal>;
  809. private:
  810. static_assert(MaxLoadFactor100 > 10 && MaxLoadFactor100 < 100,
  811. "MaxLoadFactor100 needs to be >10 && < 100");
  812. using WHash = WrapHash<Hash>;
  813. using WKeyEqual = WrapKeyEqual<KeyEqual>;
  814. // configuration defaults
  815. // make sure we have 8 elements, needed to quickly rehash mInfo
  816. static constexpr size_t InitialNumElements = sizeof(uint64_t);
  817. static constexpr uint32_t InitialInfoNumBits = 5;
  818. static constexpr uint8_t InitialInfoInc = 1U << InitialInfoNumBits;
  819. static constexpr size_t InfoMask = InitialInfoInc - 1U;
  820. static constexpr uint8_t InitialInfoHashShift = 0;
  821. using DataPool = detail::NodeAllocator<value_type, 4, 16384, IsFlat>;
  822. // type needs to be wider than uint8_t.
  823. using InfoType = uint32_t;
  824. // DataNode ////////////////////////////////////////////////////////
  825. // Primary template for the data node. We have special implementations for small and big
  826. // objects. For large objects it is assumed that swap() is fairly slow, so we allocate these
  827. // on the heap so swap merely swaps a pointer.
  828. template <typename M, bool>
  829. class DataNode {};
  830. // Small: just allocate on the stack.
  831. template <typename M>
  832. class DataNode<M, true> final {
  833. public:
  834. template <typename... Args>
  835. explicit DataNode(M& ROBIN_HOOD_UNUSED(map) /*unused*/, Args&&... args) noexcept(
  836. noexcept(value_type(std::forward<Args>(args)...)))
  837. : mData(std::forward<Args>(args)...) {}
  838. DataNode(M& ROBIN_HOOD_UNUSED(map) /*unused*/, DataNode<M, true>&& n) noexcept(
  839. std::is_nothrow_move_constructible<value_type>::value)
  840. : mData(std::move(n.mData)) {}
  841. // doesn't do anything
  842. void destroy(M& ROBIN_HOOD_UNUSED(map) /*unused*/) noexcept {}
  843. void destroyDoNotDeallocate() noexcept {}
  844. value_type const* operator->() const noexcept {
  845. return &mData;
  846. }
  847. value_type* operator->() noexcept {
  848. return &mData;
  849. }
  850. const value_type& operator*() const noexcept {
  851. return mData;
  852. }
  853. value_type& operator*() noexcept {
  854. return mData;
  855. }
  856. template <typename VT = value_type>
  857. ROBIN_HOOD(NODISCARD)
  858. typename std::enable_if<is_map, typename VT::first_type&>::type getFirst() noexcept {
  859. return mData.first;
  860. }
  861. template <typename VT = value_type>
  862. ROBIN_HOOD(NODISCARD)
  863. typename std::enable_if<is_set, VT&>::type getFirst() noexcept {
  864. return mData;
  865. }
  866. template <typename VT = value_type>
  867. ROBIN_HOOD(NODISCARD)
  868. typename std::enable_if<is_map, typename VT::first_type const&>::type
  869. getFirst() const noexcept {
  870. return mData.first;
  871. }
  872. template <typename VT = value_type>
  873. ROBIN_HOOD(NODISCARD)
  874. typename std::enable_if<is_set, VT const&>::type getFirst() const noexcept {
  875. return mData;
  876. }
  877. template <typename MT = mapped_type>
  878. ROBIN_HOOD(NODISCARD)
  879. typename std::enable_if<is_map, MT&>::type getSecond() noexcept {
  880. return mData.second;
  881. }
  882. template <typename MT = mapped_type>
  883. ROBIN_HOOD(NODISCARD)
  884. typename std::enable_if<is_set, MT const&>::type getSecond() const noexcept {
  885. return mData.second;
  886. }
  887. void swap(DataNode<M, true>& o) noexcept(
  888. noexcept(std::declval<value_type>().swap(std::declval<value_type>()))) {
  889. mData.swap(o.mData);
  890. }
  891. private:
  892. value_type mData;
  893. };
  894. // big object: allocate on heap.
  895. template <typename M>
  896. class DataNode<M, false> {
  897. public:
  898. template <typename... Args>
  899. explicit DataNode(M& map, Args&&... args)
  900. : mData(map.allocate()) {
  901. ::new (static_cast<void*>(mData)) value_type(std::forward<Args>(args)...);
  902. }
  903. DataNode(M& ROBIN_HOOD_UNUSED(map) /*unused*/, DataNode<M, false>&& n) noexcept
  904. : mData(std::move(n.mData)) {}
  905. void destroy(M& map) noexcept {
  906. // don't deallocate, just put it into list of datapool.
  907. mData->~value_type();
  908. map.deallocate(mData);
  909. }
  910. void destroyDoNotDeallocate() noexcept {
  911. mData->~value_type();
  912. }
  913. value_type const* operator->() const noexcept {
  914. return mData;
  915. }
  916. value_type* operator->() noexcept {
  917. return mData;
  918. }
  919. const value_type& operator*() const {
  920. return *mData;
  921. }
  922. value_type& operator*() {
  923. return *mData;
  924. }
  925. template <typename VT = value_type>
  926. ROBIN_HOOD(NODISCARD)
  927. typename std::enable_if<is_map, typename VT::first_type&>::type getFirst() noexcept {
  928. return mData->first;
  929. }
  930. template <typename VT = value_type>
  931. ROBIN_HOOD(NODISCARD)
  932. typename std::enable_if<is_set, VT&>::type getFirst() noexcept {
  933. return *mData;
  934. }
  935. template <typename VT = value_type>
  936. ROBIN_HOOD(NODISCARD)
  937. typename std::enable_if<is_map, typename VT::first_type const&>::type
  938. getFirst() const noexcept {
  939. return mData->first;
  940. }
  941. template <typename VT = value_type>
  942. ROBIN_HOOD(NODISCARD)
  943. typename std::enable_if<is_set, VT const&>::type getFirst() const noexcept {
  944. return *mData;
  945. }
  946. template <typename MT = mapped_type>
  947. ROBIN_HOOD(NODISCARD)
  948. typename std::enable_if<is_map, MT&>::type getSecond() noexcept {
  949. return mData->second;
  950. }
  951. template <typename MT = mapped_type>
  952. ROBIN_HOOD(NODISCARD)
  953. typename std::enable_if<is_map, MT const&>::type getSecond() const noexcept {
  954. return mData->second;
  955. }
  956. void swap(DataNode<M, false>& o) noexcept {
  957. using std::swap;
  958. swap(mData, o.mData);
  959. }
  960. private:
  961. value_type* mData;
  962. };
  963. using Node = DataNode<Self, IsFlat>;
  964. // helpers for insertKeyPrepareEmptySpot: extract first entry (only const required)
  965. ROBIN_HOOD(NODISCARD) key_type const& getFirstConst(Node const& n) const noexcept {
  966. return n.getFirst();
  967. }
  968. // in case we have void mapped_type, we are not using a pair, thus we just route k through.
  969. // No need to disable this because it's just not used if not applicable.
  970. ROBIN_HOOD(NODISCARD) key_type const& getFirstConst(key_type const& k) const noexcept {
  971. return k;
  972. }
  973. // in case we have non-void mapped_type, we have a standard robin_hood::pair
  974. template <typename Q = mapped_type>
  975. ROBIN_HOOD(NODISCARD)
  976. typename std::enable_if<!std::is_void<Q>::value, key_type const&>::type
  977. getFirstConst(value_type const& vt) const noexcept {
  978. return vt.first;
  979. }
  980. // Cloner //////////////////////////////////////////////////////////
  981. template <typename M, bool UseMemcpy>
  982. struct Cloner;
  983. // fast path: Just copy data, without allocating anything.
  984. template <typename M>
  985. struct Cloner<M, true> {
  986. void operator()(M const& source, M& target) const {
  987. auto const* const src = reinterpret_cast<char const*>(source.mKeyVals);
  988. auto* tgt = reinterpret_cast<char*>(target.mKeyVals);
  989. auto const numElementsWithBuffer = target.calcNumElementsWithBuffer(target.mMask + 1);
  990. std::copy(src, src + target.calcNumBytesTotal(numElementsWithBuffer), tgt);
  991. }
  992. };
  993. template <typename M>
  994. struct Cloner<M, false> {
  995. void operator()(M const& s, M& t) const {
  996. auto const numElementsWithBuffer = t.calcNumElementsWithBuffer(t.mMask + 1);
  997. std::copy(s.mInfo, s.mInfo + t.calcNumBytesInfo(numElementsWithBuffer), t.mInfo);
  998. for (size_t i = 0; i < numElementsWithBuffer; ++i) {
  999. if (t.mInfo[i]) {
  1000. ::new (static_cast<void*>(t.mKeyVals + i)) Node(t, *s.mKeyVals[i]);
  1001. }
  1002. }
  1003. }
  1004. };
  1005. // Destroyer ///////////////////////////////////////////////////////
  1006. template <typename M, bool IsFlatAndTrivial>
  1007. struct Destroyer {};
  1008. template <typename M>
  1009. struct Destroyer<M, true> {
  1010. void nodes(M& m) const noexcept {
  1011. m.mNumElements = 0;
  1012. }
  1013. void nodesDoNotDeallocate(M& m) const noexcept {
  1014. m.mNumElements = 0;
  1015. }
  1016. };
  1017. template <typename M>
  1018. struct Destroyer<M, false> {
  1019. void nodes(M& m) const noexcept {
  1020. m.mNumElements = 0;
  1021. // clear also resets mInfo to 0, that's sometimes not necessary.
  1022. auto const numElementsWithBuffer = m.calcNumElementsWithBuffer(m.mMask + 1);
  1023. for (size_t idx = 0; idx < numElementsWithBuffer; ++idx) {
  1024. if (0 != m.mInfo[idx]) {
  1025. Node& n = m.mKeyVals[idx];
  1026. n.destroy(m);
  1027. n.~Node();
  1028. }
  1029. }
  1030. }
  1031. void nodesDoNotDeallocate(M& m) const noexcept {
  1032. m.mNumElements = 0;
  1033. // clear also resets mInfo to 0, that's sometimes not necessary.
  1034. auto const numElementsWithBuffer = m.calcNumElementsWithBuffer(m.mMask + 1);
  1035. for (size_t idx = 0; idx < numElementsWithBuffer; ++idx) {
  1036. if (0 != m.mInfo[idx]) {
  1037. Node& n = m.mKeyVals[idx];
  1038. n.destroyDoNotDeallocate();
  1039. n.~Node();
  1040. }
  1041. }
  1042. }
  1043. };
  1044. // Iter ////////////////////////////////////////////////////////////
  1045. struct fast_forward_tag {};
  1046. // generic iterator for both const_iterator and iterator.
  1047. template <bool IsConst>
  1048. // NOLINTNEXTLINE(hicpp-special-member-functions,cppcoreguidelines-special-member-functions)
  1049. class Iter {
  1050. private:
  1051. using NodePtr = typename std::conditional<IsConst, Node const*, Node*>::type;
  1052. public:
  1053. using difference_type = std::ptrdiff_t;
  1054. using value_type = typename Self::value_type;
  1055. using reference = typename std::conditional<IsConst, value_type const&, value_type&>::type;
  1056. using pointer = typename std::conditional<IsConst, value_type const*, value_type*>::type;
  1057. using iterator_category = std::forward_iterator_tag;
  1058. // default constructed iterator can be compared to itself, but WON'T return true when
  1059. // compared to end().
  1060. Iter() = default;
  1061. // Rule of zero: nothing specified. The conversion constructor is only enabled for
  1062. // iterator to const_iterator, so it doesn't accidentally work as a copy ctor.
  1063. // Conversion constructor from iterator to const_iterator.
  1064. template <bool OtherIsConst,
  1065. typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
  1066. // NOLINTNEXTLINE(hicpp-explicit-conversions)
  1067. Iter(Iter<OtherIsConst> const& other) noexcept
  1068. : mKeyVals(other.mKeyVals)
  1069. , mInfo(other.mInfo) {}
  1070. Iter(NodePtr valPtr, uint8_t const* infoPtr) noexcept
  1071. : mKeyVals(valPtr)
  1072. , mInfo(infoPtr) {}
  1073. Iter(NodePtr valPtr, uint8_t const* infoPtr,
  1074. fast_forward_tag ROBIN_HOOD_UNUSED(tag) /*unused*/) noexcept
  1075. : mKeyVals(valPtr)
  1076. , mInfo(infoPtr) {
  1077. fastForward();
  1078. }
  1079. template <bool OtherIsConst,
  1080. typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
  1081. Iter& operator=(Iter<OtherIsConst> const& other) noexcept {
  1082. mKeyVals = other.mKeyVals;
  1083. mInfo = other.mInfo;
  1084. return *this;
  1085. }
  1086. // prefix increment. Undefined behavior if we are at end()!
  1087. Iter& operator++() noexcept {
  1088. mInfo++;
  1089. mKeyVals++;
  1090. fastForward();
  1091. return *this;
  1092. }
  1093. Iter operator++(int) noexcept {
  1094. Iter tmp = *this;
  1095. ++(*this);
  1096. return tmp;
  1097. }
  1098. reference operator*() const {
  1099. return **mKeyVals;
  1100. }
  1101. pointer operator->() const {
  1102. return &**mKeyVals;
  1103. }
  1104. template <bool O>
  1105. bool operator==(Iter<O> const& o) const noexcept {
  1106. return mKeyVals == o.mKeyVals;
  1107. }
  1108. template <bool O>
  1109. bool operator!=(Iter<O> const& o) const noexcept {
  1110. return mKeyVals != o.mKeyVals;
  1111. }
  1112. private:
  1113. // fast forward to the next non-free info byte
  1114. // I've tried a few variants that don't depend on intrinsics, but unfortunately they are
  1115. // quite a bit slower than this one. So I've reverted that change again. See map_benchmark.
  1116. void fastForward() noexcept {
  1117. size_t n = 0;
  1118. while (0U == (n = detail::unaligned_load<size_t>(mInfo))) {
  1119. mInfo += sizeof(size_t);
  1120. mKeyVals += sizeof(size_t);
  1121. }
  1122. #if defined(ROBIN_HOOD_DISABLE_INTRINSICS)
  1123. // we know for certain that within the next 8 bytes we'll find a non-zero one.
  1124. if (ROBIN_HOOD_UNLIKELY(0U == detail::unaligned_load<uint32_t>(mInfo))) {
  1125. mInfo += 4;
  1126. mKeyVals += 4;
  1127. }
  1128. if (ROBIN_HOOD_UNLIKELY(0U == detail::unaligned_load<uint16_t>(mInfo))) {
  1129. mInfo += 2;
  1130. mKeyVals += 2;
  1131. }
  1132. if (ROBIN_HOOD_UNLIKELY(0U == *mInfo)) {
  1133. mInfo += 1;
  1134. mKeyVals += 1;
  1135. }
  1136. #else
  1137. # if ROBIN_HOOD(LITTLE_ENDIAN)
  1138. auto inc = ROBIN_HOOD_COUNT_TRAILING_ZEROES(n) / 8;
  1139. # else
  1140. auto inc = ROBIN_HOOD_COUNT_LEADING_ZEROES(n) / 8;
  1141. # endif
  1142. mInfo += inc;
  1143. mKeyVals += inc;
  1144. #endif
  1145. }
  1146. friend class Table<IsFlat, MaxLoadFactor100, key_type, mapped_type, hasher, key_equal>;
  1147. NodePtr mKeyVals{nullptr};
  1148. uint8_t const* mInfo{nullptr};
  1149. };
  1150. ////////////////////////////////////////////////////////////////////
  1151. // highly performance relevant code.
  1152. // Lower bits are used for indexing into the array (2^n size)
  1153. // The upper 1-5 bits need to be a reasonable good hash, to save comparisons.
  1154. template <typename HashKey>
  1155. void keyToIdx(HashKey&& key, size_t* idx, InfoType* info) const {
  1156. // In addition to whatever hash is used, add another mul & shift so we get better hashing.
  1157. // This serves as a bad hash prevention, if the given data is
  1158. // badly mixed.
  1159. auto h = static_cast<uint64_t>(WHash::operator()(key));
  1160. h *= mHashMultiplier;
  1161. h ^= h >> 33U;
  1162. // the lower InitialInfoNumBits are reserved for info.
  1163. *info = mInfoInc + static_cast<InfoType>((h & InfoMask) >> mInfoHashShift);
  1164. *idx = (static_cast<size_t>(h) >> InitialInfoNumBits) & mMask;
  1165. }
  1166. // forwards the index by one, wrapping around at the end
  1167. void next(InfoType* info, size_t* idx) const noexcept {
  1168. *idx = *idx + 1;
  1169. *info += mInfoInc;
  1170. }
  1171. void nextWhileLess(InfoType* info, size_t* idx) const noexcept {
  1172. // unrolling this by hand did not bring any speedups.
  1173. while (*info < mInfo[*idx]) {
  1174. next(info, idx);
  1175. }
  1176. }
  1177. // Shift everything up by one element. Tries to move stuff around.
  1178. void
  1179. shiftUp(size_t startIdx,
  1180. size_t const insertion_idx) noexcept(std::is_nothrow_move_assignable<Node>::value) {
  1181. auto idx = startIdx;
  1182. ::new (static_cast<void*>(mKeyVals + idx)) Node(std::move(mKeyVals[idx - 1]));
  1183. while (--idx != insertion_idx) {
  1184. mKeyVals[idx] = std::move(mKeyVals[idx - 1]);
  1185. }
  1186. idx = startIdx;
  1187. while (idx != insertion_idx) {
  1188. ROBIN_HOOD_COUNT(shiftUp)
  1189. mInfo[idx] = static_cast<uint8_t>(mInfo[idx - 1] + mInfoInc);
  1190. if (ROBIN_HOOD_UNLIKELY(mInfo[idx] + mInfoInc > 0xFF)) {
  1191. mMaxNumElementsAllowed = 0;
  1192. }
  1193. --idx;
  1194. }
  1195. }
  1196. void shiftDown(size_t idx) noexcept(std::is_nothrow_move_assignable<Node>::value) {
  1197. // until we find one that is either empty or has zero offset.
  1198. // TODO(martinus) we don't need to move everything, just the last one for the same
  1199. // bucket.
  1200. mKeyVals[idx].destroy(*this);
  1201. // until we find one that is either empty or has zero offset.
  1202. while (mInfo[idx + 1] >= 2 * mInfoInc) {
  1203. ROBIN_HOOD_COUNT(shiftDown)
  1204. mInfo[idx] = static_cast<uint8_t>(mInfo[idx + 1] - mInfoInc);
  1205. mKeyVals[idx] = std::move(mKeyVals[idx + 1]);
  1206. ++idx;
  1207. }
  1208. mInfo[idx] = 0;
  1209. // don't destroy, we've moved it
  1210. // mKeyVals[idx].destroy(*this);
  1211. mKeyVals[idx].~Node();
  1212. }
  1213. // copy of find(), except that it returns iterator instead of const_iterator.
  1214. template <typename Other>
  1215. ROBIN_HOOD(NODISCARD)
  1216. size_t findIdx(Other const& key) const {
  1217. size_t idx{};
  1218. InfoType info{};
  1219. keyToIdx(key, &idx, &info);
  1220. do {
  1221. // unrolling this twice gives a bit of a speedup. More unrolling did not help.
  1222. if (info == mInfo[idx] &&
  1223. ROBIN_HOOD_LIKELY(WKeyEqual::operator()(key, mKeyVals[idx].getFirst()))) {
  1224. return idx;
  1225. }
  1226. next(&info, &idx);
  1227. if (info == mInfo[idx] &&
  1228. ROBIN_HOOD_LIKELY(WKeyEqual::operator()(key, mKeyVals[idx].getFirst()))) {
  1229. return idx;
  1230. }
  1231. next(&info, &idx);
  1232. } while (info <= mInfo[idx]);
  1233. // nothing found!
  1234. return mMask == 0 ? 0
  1235. : static_cast<size_t>(std::distance(
  1236. mKeyVals, reinterpret_cast_no_cast_align_warning<Node*>(mInfo)));
  1237. }
  1238. void cloneData(const Table& o) {
  1239. Cloner<Table, IsFlat && ROBIN_HOOD_IS_TRIVIALLY_COPYABLE(Node)>()(o, *this);
  1240. }
  1241. // inserts a keyval that is guaranteed to be new, e.g. when the hashmap is resized.
  1242. // @return True on success, false if something went wrong
  1243. void insert_move(Node&& keyval) {
  1244. // we don't retry, fail if overflowing
  1245. // don't need to check max num elements
  1246. if (0 == mMaxNumElementsAllowed && !try_increase_info()) {
  1247. throwOverflowError();
  1248. }
  1249. size_t idx{};
  1250. InfoType info{};
  1251. keyToIdx(keyval.getFirst(), &idx, &info);
  1252. // skip forward. Use <= because we are certain that the element is not there.
  1253. while (info <= mInfo[idx]) {
  1254. idx = idx + 1;
  1255. info += mInfoInc;
  1256. }
  1257. // key not found, so we are now exactly where we want to insert it.
  1258. auto const insertion_idx = idx;
  1259. auto const insertion_info = static_cast<uint8_t>(info);
  1260. if (ROBIN_HOOD_UNLIKELY(insertion_info + mInfoInc > 0xFF)) {
  1261. mMaxNumElementsAllowed = 0;
  1262. }
  1263. // find an empty spot
  1264. while (0 != mInfo[idx]) {
  1265. next(&info, &idx);
  1266. }
  1267. auto& l = mKeyVals[insertion_idx];
  1268. if (idx == insertion_idx) {
  1269. ::new (static_cast<void*>(&l)) Node(std::move(keyval));
  1270. } else {
  1271. shiftUp(idx, insertion_idx);
  1272. l = std::move(keyval);
  1273. }
  1274. // put at empty spot
  1275. mInfo[insertion_idx] = insertion_info;
  1276. ++mNumElements;
  1277. }
  1278. public:
  1279. using iterator = Iter<false>;
  1280. using const_iterator = Iter<true>;
  1281. Table() noexcept(noexcept(Hash()) && noexcept(KeyEqual()))
  1282. : WHash()
  1283. , WKeyEqual() {
  1284. ROBIN_HOOD_TRACE(this)
  1285. }
  1286. // Creates an empty hash map. Nothing is allocated yet, this happens at the first insert.
  1287. // This tremendously speeds up ctor & dtor of a map that never receives an element. The
  1288. // penalty is payed at the first insert, and not before. Lookup of this empty map works
  1289. // because everybody points to DummyInfoByte::b. parameter bucket_count is dictated by the
  1290. // standard, but we can ignore it.
  1291. explicit Table(
  1292. size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/, const Hash& h = Hash{},
  1293. const KeyEqual& equal = KeyEqual{}) noexcept(noexcept(Hash(h)) && noexcept(KeyEqual(equal)))
  1294. : WHash(h)
  1295. , WKeyEqual(equal) {
  1296. ROBIN_HOOD_TRACE(this)
  1297. }
  1298. template <typename Iter>
  1299. Table(Iter first, Iter last, size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/ = 0,
  1300. const Hash& h = Hash{}, const KeyEqual& equal = KeyEqual{})
  1301. : WHash(h)
  1302. , WKeyEqual(equal) {
  1303. ROBIN_HOOD_TRACE(this)
  1304. insert(first, last);
  1305. }
  1306. Table(std::initializer_list<value_type> initlist,
  1307. size_t ROBIN_HOOD_UNUSED(bucket_count) /*unused*/ = 0, const Hash& h = Hash{},
  1308. const KeyEqual& equal = KeyEqual{})
  1309. : WHash(h)
  1310. , WKeyEqual(equal) {
  1311. ROBIN_HOOD_TRACE(this)
  1312. insert(initlist.begin(), initlist.end());
  1313. }
  1314. Table(Table&& o) noexcept
  1315. : WHash(std::move(static_cast<WHash&>(o)))
  1316. , WKeyEqual(std::move(static_cast<WKeyEqual&>(o)))
  1317. , DataPool(std::move(static_cast<DataPool&>(o))) {
  1318. ROBIN_HOOD_TRACE(this)
  1319. if (o.mMask) {
  1320. mHashMultiplier = std::move(o.mHashMultiplier);
  1321. mKeyVals = std::move(o.mKeyVals);
  1322. mInfo = std::move(o.mInfo);
  1323. mNumElements = std::move(o.mNumElements);
  1324. mMask = std::move(o.mMask);
  1325. mMaxNumElementsAllowed = std::move(o.mMaxNumElementsAllowed);
  1326. mInfoInc = std::move(o.mInfoInc);
  1327. mInfoHashShift = std::move(o.mInfoHashShift);
  1328. // set other's mask to 0 so its destructor won't do anything
  1329. o.init();
  1330. }
  1331. }
  1332. Table& operator=(Table&& o) noexcept {
  1333. ROBIN_HOOD_TRACE(this)
  1334. if (&o != this) {
  1335. if (o.mMask) {
  1336. // only move stuff if the other map actually has some data
  1337. destroy();
  1338. mHashMultiplier = std::move(o.mHashMultiplier);
  1339. mKeyVals = std::move(o.mKeyVals);
  1340. mInfo = std::move(o.mInfo);
  1341. mNumElements = std::move(o.mNumElements);
  1342. mMask = std::move(o.mMask);
  1343. mMaxNumElementsAllowed = std::move(o.mMaxNumElementsAllowed);
  1344. mInfoInc = std::move(o.mInfoInc);
  1345. mInfoHashShift = std::move(o.mInfoHashShift);
  1346. WHash::operator=(std::move(static_cast<WHash&>(o)));
  1347. WKeyEqual::operator=(std::move(static_cast<WKeyEqual&>(o)));
  1348. DataPool::operator=(std::move(static_cast<DataPool&>(o)));
  1349. o.init();
  1350. } else {
  1351. // nothing in the other map => just clear us.
  1352. clear();
  1353. }
  1354. }
  1355. return *this;
  1356. }
  1357. Table(const Table& o)
  1358. : WHash(static_cast<const WHash&>(o))
  1359. , WKeyEqual(static_cast<const WKeyEqual&>(o))
  1360. , DataPool(static_cast<const DataPool&>(o)) {
  1361. ROBIN_HOOD_TRACE(this)
  1362. if (!o.empty()) {
  1363. // not empty: create an exact copy. it is also possible to just iterate through all
  1364. // elements and insert them, but copying is probably faster.
  1365. auto const numElementsWithBuffer = calcNumElementsWithBuffer(o.mMask + 1);
  1366. auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);
  1367. ROBIN_HOOD_LOG("std::malloc " << numBytesTotal << " = calcNumBytesTotal("
  1368. << numElementsWithBuffer << ")")
  1369. mHashMultiplier = o.mHashMultiplier;
  1370. mKeyVals = static_cast<Node*>(
  1371. detail::assertNotNull<std::bad_alloc>(std::malloc(numBytesTotal)));
  1372. // no need for calloc because clonData does memcpy
  1373. mInfo = reinterpret_cast<uint8_t*>(mKeyVals + numElementsWithBuffer);
  1374. mNumElements = o.mNumElements;
  1375. mMask = o.mMask;
  1376. mMaxNumElementsAllowed = o.mMaxNumElementsAllowed;
  1377. mInfoInc = o.mInfoInc;
  1378. mInfoHashShift = o.mInfoHashShift;
  1379. cloneData(o);
  1380. }
  1381. }
  1382. // Creates a copy of the given map. Copy constructor of each entry is used.
  1383. // Not sure why clang-tidy thinks this doesn't handle self assignment, it does
  1384. // NOLINTNEXTLINE(bugprone-unhandled-self-assignment,cert-oop54-cpp)
  1385. Table& operator=(Table const& o) {
  1386. ROBIN_HOOD_TRACE(this)
  1387. if (&o == this) {
  1388. // prevent assigning of itself
  1389. return *this;
  1390. }
  1391. // we keep using the old allocator and not assign the new one, because we want to keep
  1392. // the memory available. when it is the same size.
  1393. if (o.empty()) {
  1394. if (0 == mMask) {
  1395. // nothing to do, we are empty too
  1396. return *this;
  1397. }
  1398. // not empty: destroy what we have there
  1399. // clear also resets mInfo to 0, that's sometimes not necessary.
  1400. destroy();
  1401. init();
  1402. WHash::operator=(static_cast<const WHash&>(o));
  1403. WKeyEqual::operator=(static_cast<const WKeyEqual&>(o));
  1404. DataPool::operator=(static_cast<DataPool const&>(o));
  1405. return *this;
  1406. }
  1407. // clean up old stuff
  1408. Destroyer<Self, IsFlat && std::is_trivially_destructible<Node>::value>{}.nodes(*this);
  1409. if (mMask != o.mMask) {
  1410. // no luck: we don't have the same array size allocated, so we need to realloc.
  1411. if (0 != mMask) {
  1412. // only deallocate if we actually have data!
  1413. ROBIN_HOOD_LOG("std::free")
  1414. std::free(mKeyVals);
  1415. }
  1416. auto const numElementsWithBuffer = calcNumElementsWithBuffer(o.mMask + 1);
  1417. auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);
  1418. ROBIN_HOOD_LOG("std::malloc " << numBytesTotal << " = calcNumBytesTotal("
  1419. << numElementsWithBuffer << ")")
  1420. mKeyVals = static_cast<Node*>(
  1421. detail::assertNotNull<std::bad_alloc>(std::malloc(numBytesTotal)));
  1422. // no need for calloc here because cloneData performs a memcpy.
  1423. mInfo = reinterpret_cast<uint8_t*>(mKeyVals + numElementsWithBuffer);
  1424. // sentinel is set in cloneData
  1425. }
  1426. WHash::operator=(static_cast<const WHash&>(o));
  1427. WKeyEqual::operator=(static_cast<const WKeyEqual&>(o));
  1428. DataPool::operator=(static_cast<DataPool const&>(o));
  1429. mHashMultiplier = o.mHashMultiplier;
  1430. mNumElements = o.mNumElements;
  1431. mMask = o.mMask;
  1432. mMaxNumElementsAllowed = o.mMaxNumElementsAllowed;
  1433. mInfoInc = o.mInfoInc;
  1434. mInfoHashShift = o.mInfoHashShift;
  1435. cloneData(o);
  1436. return *this;
  1437. }
  1438. // Swaps everything between the two maps.
  1439. void swap(Table& o) {
  1440. ROBIN_HOOD_TRACE(this)
  1441. using std::swap;
  1442. swap(o, *this);
  1443. }
  1444. // Clears all data, without resizing.
  1445. void clear() {
  1446. ROBIN_HOOD_TRACE(this)
  1447. if (empty()) {
  1448. // don't do anything! also important because we don't want to write to
  1449. // DummyInfoByte::b, even though we would just write 0 to it.
  1450. return;
  1451. }
  1452. Destroyer<Self, IsFlat && std::is_trivially_destructible<Node>::value>{}.nodes(*this);
  1453. auto const numElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);
  1454. // clear everything, then set the sentinel again
  1455. uint8_t const z = 0;
  1456. std::fill(mInfo, mInfo + calcNumBytesInfo(numElementsWithBuffer), z);
  1457. mInfo[numElementsWithBuffer] = 1;
  1458. mInfoInc = InitialInfoInc;
  1459. mInfoHashShift = InitialInfoHashShift;
  1460. }
  1461. // Destroys the map and all it's contents.
  1462. ~Table() {
  1463. ROBIN_HOOD_TRACE(this)
  1464. destroy();
  1465. }
  1466. // Checks if both tables contain the same entries. Order is irrelevant.
  1467. bool operator==(const Table& other) const {
  1468. ROBIN_HOOD_TRACE(this)
  1469. if (other.size() != size()) {
  1470. return false;
  1471. }
  1472. for (auto const& otherEntry : other) {
  1473. if (!has(otherEntry)) {
  1474. return false;
  1475. }
  1476. }
  1477. return true;
  1478. }
  1479. bool operator!=(const Table& other) const {
  1480. ROBIN_HOOD_TRACE(this)
  1481. return !operator==(other);
  1482. }
  1483. template <typename Q = mapped_type>
  1484. typename std::enable_if<!std::is_void<Q>::value, Q&>::type operator[](const key_type& key) {
  1485. ROBIN_HOOD_TRACE(this)
  1486. auto idxAndState = insertKeyPrepareEmptySpot(key);
  1487. switch (idxAndState.second) {
  1488. case InsertionState::key_found:
  1489. break;
  1490. case InsertionState::new_node:
  1491. ::new (static_cast<void*>(&mKeyVals[idxAndState.first]))
  1492. Node(*this, std::piecewise_construct, std::forward_as_tuple(key),
  1493. std::forward_as_tuple());
  1494. break;
  1495. case InsertionState::overwrite_node:
  1496. mKeyVals[idxAndState.first] = Node(*this, std::piecewise_construct,
  1497. std::forward_as_tuple(key), std::forward_as_tuple());
  1498. break;
  1499. case InsertionState::overflow_error:
  1500. throwOverflowError();
  1501. }
  1502. return mKeyVals[idxAndState.first].getSecond();
  1503. }
  1504. template <typename Q = mapped_type>
  1505. typename std::enable_if<!std::is_void<Q>::value, Q&>::type operator[](key_type&& key) {
  1506. ROBIN_HOOD_TRACE(this)
  1507. auto idxAndState = insertKeyPrepareEmptySpot(key);
  1508. switch (idxAndState.second) {
  1509. case InsertionState::key_found:
  1510. break;
  1511. case InsertionState::new_node:
  1512. ::new (static_cast<void*>(&mKeyVals[idxAndState.first]))
  1513. Node(*this, std::piecewise_construct, std::forward_as_tuple(std::move(key)),
  1514. std::forward_as_tuple());
  1515. break;
  1516. case InsertionState::overwrite_node:
  1517. mKeyVals[idxAndState.first] =
  1518. Node(*this, std::piecewise_construct, std::forward_as_tuple(std::move(key)),
  1519. std::forward_as_tuple());
  1520. break;
  1521. case InsertionState::overflow_error:
  1522. throwOverflowError();
  1523. }
  1524. return mKeyVals[idxAndState.first].getSecond();
  1525. }
  1526. template <typename Iter>
  1527. void insert(Iter first, Iter last) {
  1528. for (; first != last; ++first) {
  1529. // value_type ctor needed because this might be called with std::pair's
  1530. insert(value_type(*first));
  1531. }
  1532. }
  1533. void insert(std::initializer_list<value_type> ilist) {
  1534. for (auto&& vt : ilist) {
  1535. insert(std::move(vt));
  1536. }
  1537. }
  1538. template <typename... Args>
  1539. std::pair<iterator, bool> emplace(Args&&... args) {
  1540. ROBIN_HOOD_TRACE(this)
  1541. Node n{*this, std::forward<Args>(args)...};
  1542. auto idxAndState = insertKeyPrepareEmptySpot(getFirstConst(n));
  1543. switch (idxAndState.second) {
  1544. case InsertionState::key_found:
  1545. n.destroy(*this);
  1546. break;
  1547. case InsertionState::new_node:
  1548. ::new (static_cast<void*>(&mKeyVals[idxAndState.first])) Node(*this, std::move(n));
  1549. break;
  1550. case InsertionState::overwrite_node:
  1551. mKeyVals[idxAndState.first] = std::move(n);
  1552. break;
  1553. case InsertionState::overflow_error:
  1554. n.destroy(*this);
  1555. throwOverflowError();
  1556. break;
  1557. }
  1558. return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),
  1559. InsertionState::key_found != idxAndState.second);
  1560. }
  1561. template <typename... Args>
  1562. iterator emplace_hint(const_iterator position, Args&&... args) {
  1563. (void)position;
  1564. return emplace(std::forward<Args>(args)...).first;
  1565. }
  1566. template <typename... Args>
  1567. std::pair<iterator, bool> try_emplace(const key_type& key, Args&&... args) {
  1568. return try_emplace_impl(key, std::forward<Args>(args)...);
  1569. }
  1570. template <typename... Args>
  1571. std::pair<iterator, bool> try_emplace(key_type&& key, Args&&... args) {
  1572. return try_emplace_impl(std::move(key), std::forward<Args>(args)...);
  1573. }
  1574. template <typename... Args>
  1575. iterator try_emplace(const_iterator hint, const key_type& key, Args&&... args) {
  1576. (void)hint;
  1577. return try_emplace_impl(key, std::forward<Args>(args)...).first;
  1578. }
  1579. template <typename... Args>
  1580. iterator try_emplace(const_iterator hint, key_type&& key, Args&&... args) {
  1581. (void)hint;
  1582. return try_emplace_impl(std::move(key), std::forward<Args>(args)...).first;
  1583. }
  1584. template <typename Mapped>
  1585. std::pair<iterator, bool> insert_or_assign(const key_type& key, Mapped&& obj) {
  1586. return insertOrAssignImpl(key, std::forward<Mapped>(obj));
  1587. }
  1588. template <typename Mapped>
  1589. std::pair<iterator, bool> insert_or_assign(key_type&& key, Mapped&& obj) {
  1590. return insertOrAssignImpl(std::move(key), std::forward<Mapped>(obj));
  1591. }
  1592. template <typename Mapped>
  1593. iterator insert_or_assign(const_iterator hint, const key_type& key, Mapped&& obj) {
  1594. (void)hint;
  1595. return insertOrAssignImpl(key, std::forward<Mapped>(obj)).first;
  1596. }
  1597. template <typename Mapped>
  1598. iterator insert_or_assign(const_iterator hint, key_type&& key, Mapped&& obj) {
  1599. (void)hint;
  1600. return insertOrAssignImpl(std::move(key), std::forward<Mapped>(obj)).first;
  1601. }
  1602. std::pair<iterator, bool> insert(const value_type& keyval) {
  1603. ROBIN_HOOD_TRACE(this)
  1604. return emplace(keyval);
  1605. }
  1606. iterator insert(const_iterator hint, const value_type& keyval) {
  1607. (void)hint;
  1608. return emplace(keyval).first;
  1609. }
  1610. std::pair<iterator, bool> insert(value_type&& keyval) {
  1611. return emplace(std::move(keyval));
  1612. }
  1613. iterator insert(const_iterator hint, value_type&& keyval) {
  1614. (void)hint;
  1615. return emplace(std::move(keyval)).first;
  1616. }
  1617. // Returns 1 if key is found, 0 otherwise.
  1618. size_t count(const key_type& key) const { // NOLINT(modernize-use-nodiscard)
  1619. ROBIN_HOOD_TRACE(this)
  1620. auto kv = mKeyVals + findIdx(key);
  1621. if (kv != reinterpret_cast_no_cast_align_warning<Node*>(mInfo)) {
  1622. return 1;
  1623. }
  1624. return 0;
  1625. }
  1626. template <typename OtherKey, typename Self_ = Self>
  1627. // NOLINTNEXTLINE(modernize-use-nodiscard)
  1628. typename std::enable_if<Self_::is_transparent, size_t>::type count(const OtherKey& key) const {
  1629. ROBIN_HOOD_TRACE(this)
  1630. auto kv = mKeyVals + findIdx(key);
  1631. if (kv != reinterpret_cast_no_cast_align_warning<Node*>(mInfo)) {
  1632. return 1;
  1633. }
  1634. return 0;
  1635. }
  1636. bool contains(const key_type& key) const { // NOLINT(modernize-use-nodiscard)
  1637. return 1U == count(key);
  1638. }
  1639. template <typename OtherKey, typename Self_ = Self>
  1640. // NOLINTNEXTLINE(modernize-use-nodiscard)
  1641. typename std::enable_if<Self_::is_transparent, bool>::type contains(const OtherKey& key) const {
  1642. return 1U == count(key);
  1643. }
  1644. // Returns a reference to the value found for key.
  1645. // Throws std::out_of_range if element cannot be found
  1646. template <typename Q = mapped_type>
  1647. // NOLINTNEXTLINE(modernize-use-nodiscard)
  1648. typename std::enable_if<!std::is_void<Q>::value, Q&>::type at(key_type const& key) {
  1649. ROBIN_HOOD_TRACE(this)
  1650. auto kv = mKeyVals + findIdx(key);
  1651. if (kv == reinterpret_cast_no_cast_align_warning<Node*>(mInfo)) {
  1652. doThrow<std::out_of_range>("key not found");
  1653. }
  1654. return kv->getSecond();
  1655. }
  1656. // Returns a reference to the value found for key.
  1657. // Throws std::out_of_range if element cannot be found
  1658. template <typename Q = mapped_type>
  1659. // NOLINTNEXTLINE(modernize-use-nodiscard)
  1660. typename std::enable_if<!std::is_void<Q>::value, Q const&>::type at(key_type const& key) const {
  1661. ROBIN_HOOD_TRACE(this)
  1662. auto kv = mKeyVals + findIdx(key);
  1663. if (kv == reinterpret_cast_no_cast_align_warning<Node*>(mInfo)) {
  1664. doThrow<std::out_of_range>("key not found");
  1665. }
  1666. return kv->getSecond();
  1667. }
  1668. const_iterator find(const key_type& key) const { // NOLINT(modernize-use-nodiscard)
  1669. ROBIN_HOOD_TRACE(this)
  1670. const size_t idx = findIdx(key);
  1671. return const_iterator{mKeyVals + idx, mInfo + idx};
  1672. }
  1673. template <typename OtherKey>
  1674. const_iterator find(const OtherKey& key, is_transparent_tag /*unused*/) const {
  1675. ROBIN_HOOD_TRACE(this)
  1676. const size_t idx = findIdx(key);
  1677. return const_iterator{mKeyVals + idx, mInfo + idx};
  1678. }
  1679. template <typename OtherKey, typename Self_ = Self>
  1680. typename std::enable_if<Self_::is_transparent, // NOLINT(modernize-use-nodiscard)
  1681. const_iterator>::type // NOLINT(modernize-use-nodiscard)
  1682. find(const OtherKey& key) const { // NOLINT(modernize-use-nodiscard)
  1683. ROBIN_HOOD_TRACE(this)
  1684. const size_t idx = findIdx(key);
  1685. return const_iterator{mKeyVals + idx, mInfo + idx};
  1686. }
  1687. iterator find(const key_type& key) {
  1688. ROBIN_HOOD_TRACE(this)
  1689. const size_t idx = findIdx(key);
  1690. return iterator{mKeyVals + idx, mInfo + idx};
  1691. }
  1692. template <typename OtherKey>
  1693. iterator find(const OtherKey& key, is_transparent_tag /*unused*/) {
  1694. ROBIN_HOOD_TRACE(this)
  1695. const size_t idx = findIdx(key);
  1696. return iterator{mKeyVals + idx, mInfo + idx};
  1697. }
  1698. template <typename OtherKey, typename Self_ = Self>
  1699. typename std::enable_if<Self_::is_transparent, iterator>::type find(const OtherKey& key) {
  1700. ROBIN_HOOD_TRACE(this)
  1701. const size_t idx = findIdx(key);
  1702. return iterator{mKeyVals + idx, mInfo + idx};
  1703. }
  1704. iterator begin() {
  1705. ROBIN_HOOD_TRACE(this)
  1706. if (empty()) {
  1707. return end();
  1708. }
  1709. return iterator(mKeyVals, mInfo, fast_forward_tag{});
  1710. }
  1711. const_iterator begin() const { // NOLINT(modernize-use-nodiscard)
  1712. ROBIN_HOOD_TRACE(this)
  1713. return cbegin();
  1714. }
  1715. const_iterator cbegin() const { // NOLINT(modernize-use-nodiscard)
  1716. ROBIN_HOOD_TRACE(this)
  1717. if (empty()) {
  1718. return cend();
  1719. }
  1720. return const_iterator(mKeyVals, mInfo, fast_forward_tag{});
  1721. }
  1722. iterator end() {
  1723. ROBIN_HOOD_TRACE(this)
  1724. // no need to supply valid info pointer: end() must not be dereferenced, and only node
  1725. // pointer is compared.
  1726. return iterator{reinterpret_cast_no_cast_align_warning<Node*>(mInfo), nullptr};
  1727. }
  1728. const_iterator end() const { // NOLINT(modernize-use-nodiscard)
  1729. ROBIN_HOOD_TRACE(this)
  1730. return cend();
  1731. }
  1732. const_iterator cend() const { // NOLINT(modernize-use-nodiscard)
  1733. ROBIN_HOOD_TRACE(this)
  1734. return const_iterator{reinterpret_cast_no_cast_align_warning<Node*>(mInfo), nullptr};
  1735. }
  1736. iterator erase(const_iterator pos) {
  1737. ROBIN_HOOD_TRACE(this)
  1738. // its safe to perform const cast here
  1739. // NOLINTNEXTLINE(cppcoreguidelines-pro-type-const-cast)
  1740. return erase(iterator{const_cast<Node*>(pos.mKeyVals), const_cast<uint8_t*>(pos.mInfo)});
  1741. }
  1742. // Erases element at pos, returns iterator to the next element.
  1743. iterator erase(iterator pos) {
  1744. ROBIN_HOOD_TRACE(this)
  1745. // we assume that pos always points to a valid entry, and not end().
  1746. auto const idx = static_cast<size_t>(pos.mKeyVals - mKeyVals);
  1747. shiftDown(idx);
  1748. --mNumElements;
  1749. if (*pos.mInfo) {
  1750. // we've backward shifted, return this again
  1751. return pos;
  1752. }
  1753. // no backward shift, return next element
  1754. return ++pos;
  1755. }
  1756. size_t erase(const key_type& key) {
  1757. ROBIN_HOOD_TRACE(this)
  1758. size_t idx{};
  1759. InfoType info{};
  1760. keyToIdx(key, &idx, &info);
  1761. // check while info matches with the source idx
  1762. do {
  1763. if (info == mInfo[idx] && WKeyEqual::operator()(key, mKeyVals[idx].getFirst())) {
  1764. shiftDown(idx);
  1765. --mNumElements;
  1766. return 1;
  1767. }
  1768. next(&info, &idx);
  1769. } while (info <= mInfo[idx]);
  1770. // nothing found to delete
  1771. return 0;
  1772. }
  1773. // reserves space for the specified number of elements. Makes sure the old data fits.
  1774. // exactly the same as reserve(c).
  1775. void rehash(size_t c) {
  1776. // forces a reserve
  1777. reserve(c, true);
  1778. }
  1779. // reserves space for the specified number of elements. Makes sure the old data fits.
  1780. // Exactly the same as rehash(c). Use rehash(0) to shrink to fit.
  1781. void reserve(size_t c) {
  1782. // reserve, but don't force rehash
  1783. reserve(c, false);
  1784. }
  1785. // If possible reallocates the map to a smaller one. This frees the underlying table.
  1786. // Does not do anything if load_factor is too large for decreasing the table's size.
  1787. void compact() {
  1788. ROBIN_HOOD_TRACE(this)
  1789. auto newSize = InitialNumElements;
  1790. while (calcMaxNumElementsAllowed(newSize) < mNumElements && newSize != 0) {
  1791. newSize *= 2;
  1792. }
  1793. if (ROBIN_HOOD_UNLIKELY(newSize == 0)) {
  1794. throwOverflowError();
  1795. }
  1796. ROBIN_HOOD_LOG("newSize > mMask + 1: " << newSize << " > " << mMask << " + 1")
  1797. // only actually do anything when the new size is bigger than the old one. This prevents to
  1798. // continuously allocate for each reserve() call.
  1799. if (newSize < mMask + 1) {
  1800. rehashPowerOfTwo(newSize, true);
  1801. }
  1802. }
  1803. size_type size() const noexcept { // NOLINT(modernize-use-nodiscard)
  1804. ROBIN_HOOD_TRACE(this)
  1805. return mNumElements;
  1806. }
  1807. size_type max_size() const noexcept { // NOLINT(modernize-use-nodiscard)
  1808. ROBIN_HOOD_TRACE(this)
  1809. return static_cast<size_type>(-1);
  1810. }
  1811. ROBIN_HOOD(NODISCARD) bool empty() const noexcept {
  1812. ROBIN_HOOD_TRACE(this)
  1813. return 0 == mNumElements;
  1814. }
  1815. float max_load_factor() const noexcept { // NOLINT(modernize-use-nodiscard)
  1816. ROBIN_HOOD_TRACE(this)
  1817. return MaxLoadFactor100 / 100.0F;
  1818. }
  1819. // Average number of elements per bucket. Since we allow only 1 per bucket
  1820. float load_factor() const noexcept { // NOLINT(modernize-use-nodiscard)
  1821. ROBIN_HOOD_TRACE(this)
  1822. return static_cast<float>(size()) / static_cast<float>(mMask + 1);
  1823. }
  1824. ROBIN_HOOD(NODISCARD) size_t mask() const noexcept {
  1825. ROBIN_HOOD_TRACE(this)
  1826. return mMask;
  1827. }
  1828. ROBIN_HOOD(NODISCARD) size_t calcMaxNumElementsAllowed(size_t maxElements) const noexcept {
  1829. if (ROBIN_HOOD_LIKELY(maxElements <= (std::numeric_limits<size_t>::max)() / 100)) {
  1830. return maxElements * MaxLoadFactor100 / 100;
  1831. }
  1832. // we might be a bit inprecise, but since maxElements is quite large that doesn't matter
  1833. return (maxElements / 100) * MaxLoadFactor100;
  1834. }
  1835. ROBIN_HOOD(NODISCARD) size_t calcNumBytesInfo(size_t numElements) const noexcept {
  1836. // we add a uint64_t, which houses the sentinel (first byte) and padding so we can load
  1837. // 64bit types.
  1838. return numElements + sizeof(uint64_t);
  1839. }
  1840. ROBIN_HOOD(NODISCARD)
  1841. size_t calcNumElementsWithBuffer(size_t numElements) const noexcept {
  1842. auto maxNumElementsAllowed = calcMaxNumElementsAllowed(numElements);
  1843. return numElements + (std::min)(maxNumElementsAllowed, (static_cast<size_t>(0xFF)));
  1844. }
  1845. // calculation only allowed for 2^n values
  1846. ROBIN_HOOD(NODISCARD) size_t calcNumBytesTotal(size_t numElements) const {
  1847. #if ROBIN_HOOD(BITNESS) == 64
  1848. return numElements * sizeof(Node) + calcNumBytesInfo(numElements);
  1849. #else
  1850. // make sure we're doing 64bit operations, so we are at least safe against 32bit overflows.
  1851. auto const ne = static_cast<uint64_t>(numElements);
  1852. auto const s = static_cast<uint64_t>(sizeof(Node));
  1853. auto const infos = static_cast<uint64_t>(calcNumBytesInfo(numElements));
  1854. auto const total64 = ne * s + infos;
  1855. auto const total = static_cast<size_t>(total64);
  1856. if (ROBIN_HOOD_UNLIKELY(static_cast<uint64_t>(total) != total64)) {
  1857. throwOverflowError();
  1858. }
  1859. return total;
  1860. #endif
  1861. }
  1862. private:
  1863. template <typename Q = mapped_type>
  1864. ROBIN_HOOD(NODISCARD)
  1865. typename std::enable_if<!std::is_void<Q>::value, bool>::type has(const value_type& e) const {
  1866. ROBIN_HOOD_TRACE(this)
  1867. auto it = find(e.first);
  1868. return it != end() && it->second == e.second;
  1869. }
  1870. template <typename Q = mapped_type>
  1871. ROBIN_HOOD(NODISCARD)
  1872. typename std::enable_if<std::is_void<Q>::value, bool>::type has(const value_type& e) const {
  1873. ROBIN_HOOD_TRACE(this)
  1874. return find(e) != end();
  1875. }
  1876. void reserve(size_t c, bool forceRehash) {
  1877. ROBIN_HOOD_TRACE(this)
  1878. auto const minElementsAllowed = (std::max)(c, mNumElements);
  1879. auto newSize = InitialNumElements;
  1880. while (calcMaxNumElementsAllowed(newSize) < minElementsAllowed && newSize != 0) {
  1881. newSize *= 2;
  1882. }
  1883. if (ROBIN_HOOD_UNLIKELY(newSize == 0)) {
  1884. throwOverflowError();
  1885. }
  1886. ROBIN_HOOD_LOG("newSize > mMask + 1: " << newSize << " > " << mMask << " + 1")
  1887. // only actually do anything when the new size is bigger than the old one. This prevents to
  1888. // continuously allocate for each reserve() call.
  1889. if (forceRehash || newSize > mMask + 1) {
  1890. rehashPowerOfTwo(newSize, false);
  1891. }
  1892. }
  1893. // reserves space for at least the specified number of elements.
  1894. // only works if numBuckets if power of two
  1895. // True on success, false otherwise
  1896. void rehashPowerOfTwo(size_t numBuckets, bool forceFree) {
  1897. ROBIN_HOOD_TRACE(this)
  1898. Node* const oldKeyVals = mKeyVals;
  1899. uint8_t const* const oldInfo = mInfo;
  1900. const size_t oldMaxElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);
  1901. // resize operation: move stuff
  1902. initData(numBuckets);
  1903. if (oldMaxElementsWithBuffer > 1) {
  1904. for (size_t i = 0; i < oldMaxElementsWithBuffer; ++i) {
  1905. if (oldInfo[i] != 0) {
  1906. // might throw an exception, which is really bad since we are in the middle of
  1907. // moving stuff.
  1908. insert_move(std::move(oldKeyVals[i]));
  1909. // destroy the node but DON'T destroy the data.
  1910. oldKeyVals[i].~Node();
  1911. }
  1912. }
  1913. // this check is not necessary as it's guarded by the previous if, but it helps
  1914. // silence g++'s overeager "attempt to free a non-heap object 'map'
  1915. // [-Werror=free-nonheap-object]" warning.
  1916. if (oldKeyVals != reinterpret_cast_no_cast_align_warning<Node*>(&mMask)) {
  1917. // don't destroy old data: put it into the pool instead
  1918. if (forceFree) {
  1919. std::free(oldKeyVals);
  1920. } else {
  1921. DataPool::addOrFree(oldKeyVals, calcNumBytesTotal(oldMaxElementsWithBuffer));
  1922. }
  1923. }
  1924. }
  1925. }
  1926. ROBIN_HOOD(NOINLINE) void throwOverflowError() const {
  1927. #if ROBIN_HOOD(HAS_EXCEPTIONS)
  1928. throw std::overflow_error("robin_hood::map overflow");
  1929. #else
  1930. abort();
  1931. #endif
  1932. }
  1933. template <typename OtherKey, typename... Args>
  1934. std::pair<iterator, bool> try_emplace_impl(OtherKey&& key, Args&&... args) {
  1935. ROBIN_HOOD_TRACE(this)
  1936. auto idxAndState = insertKeyPrepareEmptySpot(key);
  1937. switch (idxAndState.second) {
  1938. case InsertionState::key_found:
  1939. break;
  1940. case InsertionState::new_node:
  1941. ::new (static_cast<void*>(&mKeyVals[idxAndState.first])) Node(
  1942. *this, std::piecewise_construct, std::forward_as_tuple(std::forward<OtherKey>(key)),
  1943. std::forward_as_tuple(std::forward<Args>(args)...));
  1944. break;
  1945. case InsertionState::overwrite_node:
  1946. mKeyVals[idxAndState.first] = Node(*this, std::piecewise_construct,
  1947. std::forward_as_tuple(std::forward<OtherKey>(key)),
  1948. std::forward_as_tuple(std::forward<Args>(args)...));
  1949. break;
  1950. case InsertionState::overflow_error:
  1951. throwOverflowError();
  1952. break;
  1953. }
  1954. return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),
  1955. InsertionState::key_found != idxAndState.second);
  1956. }
  1957. template <typename OtherKey, typename Mapped>
  1958. std::pair<iterator, bool> insertOrAssignImpl(OtherKey&& key, Mapped&& obj) {
  1959. ROBIN_HOOD_TRACE(this)
  1960. auto idxAndState = insertKeyPrepareEmptySpot(key);
  1961. switch (idxAndState.second) {
  1962. case InsertionState::key_found:
  1963. mKeyVals[idxAndState.first].getSecond() = std::forward<Mapped>(obj);
  1964. break;
  1965. case InsertionState::new_node:
  1966. ::new (static_cast<void*>(&mKeyVals[idxAndState.first])) Node(
  1967. *this, std::piecewise_construct, std::forward_as_tuple(std::forward<OtherKey>(key)),
  1968. std::forward_as_tuple(std::forward<Mapped>(obj)));
  1969. break;
  1970. case InsertionState::overwrite_node:
  1971. mKeyVals[idxAndState.first] = Node(*this, std::piecewise_construct,
  1972. std::forward_as_tuple(std::forward<OtherKey>(key)),
  1973. std::forward_as_tuple(std::forward<Mapped>(obj)));
  1974. break;
  1975. case InsertionState::overflow_error:
  1976. throwOverflowError();
  1977. break;
  1978. }
  1979. return std::make_pair(iterator(mKeyVals + idxAndState.first, mInfo + idxAndState.first),
  1980. InsertionState::key_found != idxAndState.second);
  1981. }
  1982. void initData(size_t max_elements) {
  1983. mNumElements = 0;
  1984. mMask = max_elements - 1;
  1985. mMaxNumElementsAllowed = calcMaxNumElementsAllowed(max_elements);
  1986. auto const numElementsWithBuffer = calcNumElementsWithBuffer(max_elements);
  1987. // malloc & zero mInfo. Faster than calloc everything.
  1988. auto const numBytesTotal = calcNumBytesTotal(numElementsWithBuffer);
  1989. ROBIN_HOOD_LOG("std::calloc " << numBytesTotal << " = calcNumBytesTotal("
  1990. << numElementsWithBuffer << ")")
  1991. mKeyVals = reinterpret_cast<Node*>(
  1992. detail::assertNotNull<std::bad_alloc>(std::malloc(numBytesTotal)));
  1993. mInfo = reinterpret_cast<uint8_t*>(mKeyVals + numElementsWithBuffer);
  1994. std::memset(mInfo, 0, numBytesTotal - numElementsWithBuffer * sizeof(Node));
  1995. // set sentinel
  1996. mInfo[numElementsWithBuffer] = 1;
  1997. mInfoInc = InitialInfoInc;
  1998. mInfoHashShift = InitialInfoHashShift;
  1999. }
  2000. enum class InsertionState { overflow_error, key_found, new_node, overwrite_node };
  2001. // Finds key, and if not already present prepares a spot where to pot the key & value.
  2002. // This potentially shifts nodes out of the way, updates mInfo and number of inserted
  2003. // elements, so the only operation left to do is create/assign a new node at that spot.
  2004. template <typename OtherKey>
  2005. std::pair<size_t, InsertionState> insertKeyPrepareEmptySpot(OtherKey&& key) {
  2006. for (int i = 0; i < 256; ++i) {
  2007. size_t idx{};
  2008. InfoType info{};
  2009. keyToIdx(key, &idx, &info);
  2010. nextWhileLess(&info, &idx);
  2011. // while we potentially have a match
  2012. while (info == mInfo[idx]) {
  2013. if (WKeyEqual::operator()(key, mKeyVals[idx].getFirst())) {
  2014. // key already exists, do NOT insert.
  2015. // see http://en.cppreference.com/w/cpp/container/unordered_map/insert
  2016. return std::make_pair(idx, InsertionState::key_found);
  2017. }
  2018. next(&info, &idx);
  2019. }
  2020. // unlikely that this evaluates to true
  2021. if (ROBIN_HOOD_UNLIKELY(mNumElements >= mMaxNumElementsAllowed)) {
  2022. if (!increase_size()) {
  2023. return std::make_pair(size_t(0), InsertionState::overflow_error);
  2024. }
  2025. continue;
  2026. }
  2027. // key not found, so we are now exactly where we want to insert it.
  2028. auto const insertion_idx = idx;
  2029. auto const insertion_info = info;
  2030. if (ROBIN_HOOD_UNLIKELY(insertion_info + mInfoInc > 0xFF)) {
  2031. mMaxNumElementsAllowed = 0;
  2032. }
  2033. // find an empty spot
  2034. while (0 != mInfo[idx]) {
  2035. next(&info, &idx);
  2036. }
  2037. if (idx != insertion_idx) {
  2038. shiftUp(idx, insertion_idx);
  2039. }
  2040. // put at empty spot
  2041. mInfo[insertion_idx] = static_cast<uint8_t>(insertion_info);
  2042. ++mNumElements;
  2043. return std::make_pair(insertion_idx, idx == insertion_idx
  2044. ? InsertionState::new_node
  2045. : InsertionState::overwrite_node);
  2046. }
  2047. // enough attempts failed, so finally give up.
  2048. return std::make_pair(size_t(0), InsertionState::overflow_error);
  2049. }
  2050. bool try_increase_info() {
  2051. ROBIN_HOOD_LOG("mInfoInc=" << mInfoInc << ", numElements=" << mNumElements
  2052. << ", maxNumElementsAllowed="
  2053. << calcMaxNumElementsAllowed(mMask + 1))
  2054. if (mInfoInc <= 2) {
  2055. // need to be > 2 so that shift works (otherwise undefined behavior!)
  2056. return false;
  2057. }
  2058. // we got space left, try to make info smaller
  2059. mInfoInc = static_cast<uint8_t>(mInfoInc >> 1U);
  2060. // remove one bit of the hash, leaving more space for the distance info.
  2061. // This is extremely fast because we can operate on 8 bytes at once.
  2062. ++mInfoHashShift;
  2063. auto const numElementsWithBuffer = calcNumElementsWithBuffer(mMask + 1);
  2064. for (size_t i = 0; i < numElementsWithBuffer; i += 8) {
  2065. auto val = unaligned_load<uint64_t>(mInfo + i);
  2066. val = (val >> 1U) & UINT64_C(0x7f7f7f7f7f7f7f7f);
  2067. std::memcpy(mInfo + i, &val, sizeof(val));
  2068. }
  2069. // update sentinel, which might have been cleared out!
  2070. mInfo[numElementsWithBuffer] = 1;
  2071. mMaxNumElementsAllowed = calcMaxNumElementsAllowed(mMask + 1);
  2072. return true;
  2073. }
  2074. // True if resize was possible, false otherwise
  2075. bool increase_size() {
  2076. // nothing allocated yet? just allocate InitialNumElements
  2077. if (0 == mMask) {
  2078. initData(InitialNumElements);
  2079. return true;
  2080. }
  2081. auto const maxNumElementsAllowed = calcMaxNumElementsAllowed(mMask + 1);
  2082. if (mNumElements < maxNumElementsAllowed && try_increase_info()) {
  2083. return true;
  2084. }
  2085. ROBIN_HOOD_LOG("mNumElements=" << mNumElements << ", maxNumElementsAllowed="
  2086. << maxNumElementsAllowed << ", load="
  2087. << (static_cast<double>(mNumElements) * 100.0 /
  2088. (static_cast<double>(mMask) + 1)))
  2089. if (mNumElements * 2 < calcMaxNumElementsAllowed(mMask + 1)) {
  2090. // we have to resize, even though there would still be plenty of space left!
  2091. // Try to rehash instead. Delete freed memory so we don't steadyily increase mem in case
  2092. // we have to rehash a few times
  2093. nextHashMultiplier();
  2094. rehashPowerOfTwo(mMask + 1, true);
  2095. } else {
  2096. // we've reached the capacity of the map, so the hash seems to work nice. Keep using it.
  2097. rehashPowerOfTwo((mMask + 1) * 2, false);
  2098. }
  2099. return true;
  2100. }
  2101. void nextHashMultiplier() {
  2102. // adding an *even* number, so that the multiplier will always stay odd. This is necessary
  2103. // so that the hash stays a mixing function (and thus doesn't have any information loss).
  2104. mHashMultiplier += UINT64_C(0xc4ceb9fe1a85ec54);
  2105. }
  2106. void destroy() {
  2107. if (0 == mMask) {
  2108. // don't deallocate!
  2109. return;
  2110. }
  2111. Destroyer<Self, IsFlat && std::is_trivially_destructible<Node>::value>{}
  2112. .nodesDoNotDeallocate(*this);
  2113. // This protection against not deleting mMask shouldn't be needed as it's sufficiently
  2114. // protected with the 0==mMask check, but I have this anyways because g++ 7 otherwise
  2115. // reports a compile error: attempt to free a non-heap object 'fm'
  2116. // [-Werror=free-nonheap-object]
  2117. if (mKeyVals != reinterpret_cast_no_cast_align_warning<Node*>(&mMask)) {
  2118. ROBIN_HOOD_LOG("std::free")
  2119. std::free(mKeyVals);
  2120. }
  2121. }
  2122. void init() noexcept {
  2123. mKeyVals = reinterpret_cast_no_cast_align_warning<Node*>(&mMask);
  2124. mInfo = reinterpret_cast<uint8_t*>(&mMask);
  2125. mNumElements = 0;
  2126. mMask = 0;
  2127. mMaxNumElementsAllowed = 0;
  2128. mInfoInc = InitialInfoInc;
  2129. mInfoHashShift = InitialInfoHashShift;
  2130. }
  2131. // members are sorted so no padding occurs
  2132. uint64_t mHashMultiplier = UINT64_C(0xc4ceb9fe1a85ec53); // 8 byte 8
  2133. Node* mKeyVals = reinterpret_cast_no_cast_align_warning<Node*>(&mMask); // 8 byte 16
  2134. uint8_t* mInfo = reinterpret_cast<uint8_t*>(&mMask); // 8 byte 24
  2135. size_t mNumElements = 0; // 8 byte 32
  2136. size_t mMask = 0; // 8 byte 40
  2137. size_t mMaxNumElementsAllowed = 0; // 8 byte 48
  2138. InfoType mInfoInc = InitialInfoInc; // 4 byte 52
  2139. InfoType mInfoHashShift = InitialInfoHashShift; // 4 byte 56
  2140. // 16 byte 56 if NodeAllocator
  2141. };
  2142. } // namespace detail
  2143. // map
  2144. template <typename Key, typename T, typename Hash = hash<Key>,
  2145. typename KeyEqual = std::equal_to<Key>, size_t MaxLoadFactor100 = 80>
  2146. using unordered_flat_map = detail::Table<true, MaxLoadFactor100, Key, T, Hash, KeyEqual>;
  2147. template <typename Key, typename T, typename Hash = hash<Key>,
  2148. typename KeyEqual = std::equal_to<Key>, size_t MaxLoadFactor100 = 80>
  2149. using unordered_node_map = detail::Table<false, MaxLoadFactor100, Key, T, Hash, KeyEqual>;
  2150. template <typename Key, typename T, typename Hash = hash<Key>,
  2151. typename KeyEqual = std::equal_to<Key>, size_t MaxLoadFactor100 = 80>
  2152. using unordered_map =
  2153. detail::Table<sizeof(robin_hood::pair<Key, T>) <= sizeof(size_t) * 6 &&
  2154. std::is_nothrow_move_constructible<robin_hood::pair<Key, T>>::value &&
  2155. std::is_nothrow_move_assignable<robin_hood::pair<Key, T>>::value,
  2156. MaxLoadFactor100, Key, T, Hash, KeyEqual>;
  2157. // set
  2158. template <typename Key, typename Hash = hash<Key>, typename KeyEqual = std::equal_to<Key>,
  2159. size_t MaxLoadFactor100 = 80>
  2160. using unordered_flat_set = detail::Table<true, MaxLoadFactor100, Key, void, Hash, KeyEqual>;
  2161. template <typename Key, typename Hash = hash<Key>, typename KeyEqual = std::equal_to<Key>,
  2162. size_t MaxLoadFactor100 = 80>
  2163. using unordered_node_set = detail::Table<false, MaxLoadFactor100, Key, void, Hash, KeyEqual>;
  2164. template <typename Key, typename Hash = hash<Key>, typename KeyEqual = std::equal_to<Key>,
  2165. size_t MaxLoadFactor100 = 80>
  2166. using unordered_set = detail::Table<sizeof(Key) <= sizeof(size_t) * 6 &&
  2167. std::is_nothrow_move_constructible<Key>::value &&
  2168. std::is_nothrow_move_assignable<Key>::value,
  2169. MaxLoadFactor100, Key, void, Hash, KeyEqual>;
  2170. } // namespace robin_hood
  2171. #endif