Debian Codegraph @

3rdparty/tracy/server/tracy_robin_hood.h

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