Infinity Engine v0.6.20
C++ API Documentation
Loading...
Searching...
No Matches
unordered_dense.h
1// INFINITY_API_PUBLIC
2
4
5// A fast & densely stored hashmap and hashset based on robin-hood backward shift deletion.
6// Version 4.5.0
7// https://github.com/martinus/unordered_dense
8//
9// Licensed under the MIT License <http://opensource.org/licenses/MIT>.
10// SPDX-License-Identifier: MIT
11// Copyright (c) 2022-2024 Martin Leitner-Ankerl <martin.ankerl@gmail.com>
12//
13// Permission is hereby granted, free of charge, to any person obtaining a copy
14// of this software and associated documentation files (the "Software"), to deal
15// in the Software without restriction, including without limitation the rights
16// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17// copies of the Software, and to permit persons to whom the Software is
18// furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included in all
21// copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29// SOFTWARE.
30
31#ifndef ANKERL_UNORDERED_DENSE_H
32#define ANKERL_UNORDERED_DENSE_H
33
34// see https://semver.org/spec/v2.0.0.html
35#define ANKERL_UNORDERED_DENSE_VERSION_MAJOR 4 // NOLINT(cppcoreguidelines-macro-usage) incompatible API changes
36#define ANKERL_UNORDERED_DENSE_VERSION_MINOR 5 // NOLINT(cppcoreguidelines-macro-usage) backwards compatible functionality
37#define ANKERL_UNORDERED_DENSE_VERSION_PATCH 0 // NOLINT(cppcoreguidelines-macro-usage) backwards compatible bug fixes
38
39// API versioning with inline namespace, see https://www.foonathan.net/2018/11/inline-namespaces/
40
41// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
42#define ANKERL_UNORDERED_DENSE_VERSION_CONCAT1(major, minor, patch) v##major##_##minor##_##patch
43// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
44#define ANKERL_UNORDERED_DENSE_VERSION_CONCAT(major, minor, patch) ANKERL_UNORDERED_DENSE_VERSION_CONCAT1(major, minor, patch)
45#define ANKERL_UNORDERED_DENSE_NAMESPACE \
46 ANKERL_UNORDERED_DENSE_VERSION_CONCAT( \
47 ANKERL_UNORDERED_DENSE_VERSION_MAJOR, ANKERL_UNORDERED_DENSE_VERSION_MINOR, ANKERL_UNORDERED_DENSE_VERSION_PATCH)
48
49#if defined(_MSVC_LANG)
50# define ANKERL_UNORDERED_DENSE_CPP_VERSION _MSVC_LANG
51#else
52# define ANKERL_UNORDERED_DENSE_CPP_VERSION __cplusplus
53#endif
54
55#if defined(__GNUC__)
56// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
57# define ANKERL_UNORDERED_DENSE_PACK(decl) decl __attribute__((__packed__))
58#elif defined(_MSC_VER)
59// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
60# define ANKERL_UNORDERED_DENSE_PACK(decl) __pragma(pack(push, 1)) decl __pragma(pack(pop))
61#endif
62
63// exceptions
64#if defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)
65# define ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() 1 // NOLINT(cppcoreguidelines-macro-usage)
66#else
67# define ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() 0 // NOLINT(cppcoreguidelines-macro-usage)
68#endif
69#ifdef _MSC_VER
70# define ANKERL_UNORDERED_DENSE_NOINLINE __declspec(noinline)
71#else
72# define ANKERL_UNORDERED_DENSE_NOINLINE __attribute__((noinline))
73#endif
74
75// defined in unordered_dense.cpp
76#if !defined(ANKERL_UNORDERED_DENSE_EXPORT)
77# define ANKERL_UNORDERED_DENSE_EXPORT
78#endif
79
80#if ANKERL_UNORDERED_DENSE_CPP_VERSION < 201703L
81# error ankerl::unordered_dense requires C++17 or higher
82#else
83# include <array> // for array
84# include <cstdint> // for uint64_t, uint32_t, uint8_t, UINT64_C
85# include <cstring> // for size_t, memcpy, memset
86# include <functional> // for equal_to, hash
87# include <initializer_list> // for initializer_list
88# include <iterator> // for pair, distance
89# include <limits> // for numeric_limits
90# include <memory> // for allocator, allocator_traits, shared_ptr
91# include <optional> // for optional
92# include <stdexcept> // for out_of_range
93# include <string> // for basic_string
94# include <string_view> // for basic_string_view, hash
95# include <tuple> // for forward_as_tuple
96# include <type_traits> // for enable_if_t, declval, conditional_t, ena...
97# include <utility> // for forward, exchange, pair, as_const, piece...
98# include <vector> // for vector
99# if ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS() == 0
100# include <cstdlib> // for abort
101# endif
102
103# if defined(__has_include) && !defined(ANKERL_UNORDERED_DENSE_DISABLE_PMR)
104# if __has_include(<memory_resource>)
105# define ANKERL_UNORDERED_DENSE_PMR std::pmr // NOLINT(cppcoreguidelines-macro-usage)
106# include <memory_resource> // for polymorphic_allocator
107# elif __has_include(<experimental/memory_resource>)
108# define ANKERL_UNORDERED_DENSE_PMR std::experimental::pmr // NOLINT(cppcoreguidelines-macro-usage)
109# include <experimental/memory_resource> // for polymorphic_allocator
110# endif
111# endif
112
113# if defined(_MSC_VER) && defined(_M_X64)
114# include <intrin.h>
115# pragma intrinsic(_umul128)
116# endif
117
118# if defined(__GNUC__) || defined(__INTEL_COMPILER) || defined(__clang__)
119# define ANKERL_UNORDERED_DENSE_LIKELY(x) __builtin_expect(x, 1) // NOLINT(cppcoreguidelines-macro-usage)
120# define ANKERL_UNORDERED_DENSE_UNLIKELY(x) __builtin_expect(x, 0) // NOLINT(cppcoreguidelines-macro-usage)
121# else
122# define ANKERL_UNORDERED_DENSE_LIKELY(x) (x) // NOLINT(cppcoreguidelines-macro-usage)
123# define ANKERL_UNORDERED_DENSE_UNLIKELY(x) (x) // NOLINT(cppcoreguidelines-macro-usage)
124# endif
125
126namespace ankerl::unordered_dense {
127inline namespace ANKERL_UNORDERED_DENSE_NAMESPACE {
128
129namespace detail {
130
131# if ANKERL_UNORDERED_DENSE_HAS_EXCEPTIONS()
132
133// make sure this is not inlined as it is slow and dramatically enlarges code, thus making other
134// inlinings more difficult. Throws are also generally the slow path.
135[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_key_not_found() {
136 throw std::out_of_range("ankerl::unordered_dense::map::at(): key not found");
137}
138[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_bucket_overflow() {
139 throw std::overflow_error("ankerl::unordered_dense: reached max bucket size, cannot increase size");
140}
141[[noreturn]] inline ANKERL_UNORDERED_DENSE_NOINLINE void on_error_too_many_elements() {
142 throw std::out_of_range("ankerl::unordered_dense::map::replace(): too many elements");
143}
144
145# else
146
147[[noreturn]] inline void on_error_key_not_found() {
148 abort();
149}
150[[noreturn]] inline void on_error_bucket_overflow() {
151 abort();
152}
153[[noreturn]] inline void on_error_too_many_elements() {
154 abort();
155}
156
157# endif
158
159} // namespace detail
160
161// hash ///////////////////////////////////////////////////////////////////////
162
163// This is a stripped-down implementation of wyhash: https://github.com/wangyi-fudan/wyhash
164// No big-endian support (because different values on different machines don't matter),
165// hardcodes seed and the secret, reformats the code, and clang-tidy fixes.
166namespace detail::wyhash {
167
168inline void mum(uint64_t* a, uint64_t* b) {
169# if defined(__SIZEOF_INT128__)
170 __uint128_t r = *a;
171 r *= *b;
172 *a = static_cast<uint64_t>(r);
173 *b = static_cast<uint64_t>(r >> 64U);
174# elif defined(_MSC_VER) && defined(_M_X64)
175 *a = _umul128(*a, *b, b);
176# else
177 uint64_t ha = *a >> 32U;
178 uint64_t hb = *b >> 32U;
179 uint64_t la = static_cast<uint32_t>(*a);
180 uint64_t lb = static_cast<uint32_t>(*b);
181 uint64_t hi{};
182 uint64_t lo{};
183 uint64_t rh = ha * hb;
184 uint64_t rm0 = ha * lb;
185 uint64_t rm1 = hb * la;
186 uint64_t rl = la * lb;
187 uint64_t t = rl + (rm0 << 32U);
188 auto c = static_cast<uint64_t>(t < rl);
189 lo = t + (rm1 << 32U);
190 c += static_cast<uint64_t>(lo < t);
191 hi = rh + (rm0 >> 32U) + (rm1 >> 32U) + c;
192 *a = lo;
193 *b = hi;
194# endif
195}
196
197// multiply and xor mix function, aka MUM
198[[nodiscard]] inline auto mix(uint64_t a, uint64_t b) -> uint64_t {
199 mum(&a, &b);
200 return a ^ b;
201}
202
203// read functions. WARNING: we don't care about endianness, so results are different on big endian!
204[[nodiscard]] inline auto r8(const uint8_t* p) -> uint64_t {
205 uint64_t v{};
206 std::memcpy(&v, p, 8U);
207 return v;
208}
209
210[[nodiscard]] inline auto r4(const uint8_t* p) -> uint64_t {
211 uint32_t v{};
212 std::memcpy(&v, p, 4);
213 return v;
214}
215
216// reads 1, 2, or 3 bytes
217[[nodiscard]] inline auto r3(const uint8_t* p, size_t k) -> uint64_t {
218 return (static_cast<uint64_t>(p[0]) << 16U) | (static_cast<uint64_t>(p[k >> 1U]) << 8U) | p[k - 1];
219}
220
221[[maybe_unused]] [[nodiscard]] inline auto hash(void const* key, size_t len) -> uint64_t {
222 static constexpr auto secret = std::array{UINT64_C(0xa0761d6478bd642f),
223 UINT64_C(0xe7037ed1a0b428db),
224 UINT64_C(0x8ebc6af09c88c6e3),
225 UINT64_C(0x589965cc75374cc3)};
226
227 auto const* p = static_cast<uint8_t const*>(key);
228 uint64_t seed = secret[0];
229 uint64_t a{};
230 uint64_t b{};
231 if (ANKERL_UNORDERED_DENSE_LIKELY(len <= 16)) {
232 if (ANKERL_UNORDERED_DENSE_LIKELY(len >= 4)) {
233 a = (r4(p) << 32U) | r4(p + ((len >> 3U) << 2U));
234 b = (r4(p + len - 4) << 32U) | r4(p + len - 4 - ((len >> 3U) << 2U));
235 } else if (ANKERL_UNORDERED_DENSE_LIKELY(len > 0)) {
236 a = r3(p, len);
237 b = 0;
238 } else {
239 a = 0;
240 b = 0;
241 }
242 } else {
243 size_t i = len;
244 if (ANKERL_UNORDERED_DENSE_UNLIKELY(i > 48)) {
245 uint64_t see1 = seed;
246 uint64_t see2 = seed;
247 do {
248 seed = mix(r8(p) ^ secret[1], r8(p + 8) ^ seed);
249 see1 = mix(r8(p + 16) ^ secret[2], r8(p + 24) ^ see1);
250 see2 = mix(r8(p + 32) ^ secret[3], r8(p + 40) ^ see2);
251 p += 48;
252 i -= 48;
253 } while (ANKERL_UNORDERED_DENSE_LIKELY(i > 48));
254 seed ^= see1 ^ see2;
255 }
256 while (ANKERL_UNORDERED_DENSE_UNLIKELY(i > 16)) {
257 seed = mix(r8(p) ^ secret[1], r8(p + 8) ^ seed);
258 i -= 16;
259 p += 16;
260 }
261 a = r8(p + i - 16);
262 b = r8(p + i - 8);
263 }
264
265 return mix(secret[1] ^ len, mix(a ^ secret[1], b ^ seed));
266}
267
268[[nodiscard]] inline auto hash(uint64_t x) -> uint64_t {
269 return detail::wyhash::mix(x, UINT64_C(0x9E3779B97F4A7C15));
270}
271
272} // namespace detail::wyhash
273
274ANKERL_UNORDERED_DENSE_EXPORT template <typename T, typename Enable = void>
275struct hash {
276 auto operator()(T const& obj) const noexcept(noexcept(std::declval<std::hash<T>>().operator()(std::declval<T const&>())))
277 -> uint64_t {
278 return std::hash<T>{}(obj);
279 }
280};
281
282template <typename T>
283struct hash<T, typename std::hash<T>::is_avalanching> {
284 using is_avalanching = void;
285 auto operator()(T const& obj) const noexcept(noexcept(std::declval<std::hash<T>>().operator()(std::declval<T const&>())))
286 -> uint64_t {
287 return std::hash<T>{}(obj);
288 }
289};
290
291template <typename CharT>
292struct hash<std::basic_string<CharT>> {
293 using is_avalanching = void;
294 auto operator()(std::basic_string<CharT> const& str) const noexcept -> uint64_t {
295 return detail::wyhash::hash(str.data(), sizeof(CharT) * str.size());
296 }
297};
298
299template <typename CharT>
300struct hash<std::basic_string_view<CharT>> {
301 using is_avalanching = void;
302 auto operator()(std::basic_string_view<CharT> const& sv) const noexcept -> uint64_t {
303 return detail::wyhash::hash(sv.data(), sizeof(CharT) * sv.size());
304 }
305};
306
307template <class T>
308struct hash<T*> {
309 using is_avalanching = void;
310 auto operator()(T* ptr) const noexcept -> uint64_t {
311 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
312 return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr));
313 }
314};
315
316template <class T>
317struct hash<std::unique_ptr<T>> {
318 using is_avalanching = void;
319 auto operator()(std::unique_ptr<T> const& ptr) const noexcept -> uint64_t {
320 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
321 return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr.get()));
322 }
323};
324
325template <class T>
326struct hash<std::shared_ptr<T>> {
327 using is_avalanching = void;
328 auto operator()(std::shared_ptr<T> const& ptr) const noexcept -> uint64_t {
329 // NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
330 return detail::wyhash::hash(reinterpret_cast<uintptr_t>(ptr.get()));
331 }
332};
333
334template <typename Enum>
335struct hash<Enum, typename std::enable_if<std::is_enum<Enum>::value>::type> {
336 using is_avalanching = void;
337 auto operator()(Enum e) const noexcept -> uint64_t {
338 using underlying = typename std::underlying_type_t<Enum>;
339 return detail::wyhash::hash(static_cast<underlying>(e));
340 }
341};
342
343template <typename... Args>
344struct tuple_hash_helper {
345 // Converts the value into 64bit. If it is an integral type, just cast it. Mixing is doing the rest.
346 // If it isn't an integral we need to hash it.
347 template <typename Arg>
348 [[nodiscard]] constexpr static auto to64(Arg const& arg) -> uint64_t {
349 if constexpr (std::is_integral_v<Arg> || std::is_enum_v<Arg>) {
350 return static_cast<uint64_t>(arg);
351 } else {
352 return hash<Arg>{}(arg);
353 }
354 }
355
356 [[nodiscard]] static auto mix64(uint64_t state, uint64_t v) -> uint64_t {
357 return detail::wyhash::mix(state + v, uint64_t{0x9ddfea08eb382d69});
358 }
359
360 // Creates a buffer that holds all the data from each element of the tuple. If possible we memcpy the data directly. If
361 // not, we hash the object and use this for the array. Size of the array is known at compile time, and memcpy is optimized
362 // away, so filling the buffer is highly efficient. Finally, call wyhash with this buffer.
363 template <typename T, size_t... Idx>
364 [[nodiscard]] static auto calc_hash(T const& t, std::index_sequence<Idx...>) noexcept -> uint64_t {
365 auto h = uint64_t{};
366 ((h = mix64(h, to64(std::get<Idx>(t)))), ...);
367 return h;
368 }
369};
370
371template <typename... Args>
372struct hash<std::tuple<Args...>> : tuple_hash_helper<Args...> {
373 using is_avalanching = void;
374 auto operator()(std::tuple<Args...> const& t) const noexcept -> uint64_t {
375 return tuple_hash_helper<Args...>::calc_hash(t, std::index_sequence_for<Args...>{});
376 }
377};
378
379template <typename A, typename B>
380struct hash<std::pair<A, B>> : tuple_hash_helper<A, B> {
381 using is_avalanching = void;
382 auto operator()(std::pair<A, B> const& t) const noexcept -> uint64_t {
383 return tuple_hash_helper<A, B>::calc_hash(t, std::index_sequence_for<A, B>{});
384 }
385};
386
387// NOLINTNEXTLINE(cppcoreguidelines-macro-usage)
388# define ANKERL_UNORDERED_DENSE_HASH_STATICCAST(T) \
389 template <> \
390 struct hash<T> { \
391 using is_avalanching = void; \
392 auto operator()(T const& obj) const noexcept -> uint64_t { \
393 return detail::wyhash::hash(static_cast<uint64_t>(obj)); \
394 } \
395 }
396
397# if defined(__GNUC__) && !defined(__clang__)
398# pragma GCC diagnostic push
399# pragma GCC diagnostic ignored "-Wuseless-cast"
400# endif
401// see https://en.cppreference.com/w/cpp/utility/hash
402ANKERL_UNORDERED_DENSE_HASH_STATICCAST(bool);
403ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char);
404ANKERL_UNORDERED_DENSE_HASH_STATICCAST(signed char);
405ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned char);
406# if ANKERL_UNORDERED_DENSE_CPP_VERSION >= 202002L && defined(__cpp_char8_t)
407ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char8_t);
408# endif
409ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char16_t);
410ANKERL_UNORDERED_DENSE_HASH_STATICCAST(char32_t);
411ANKERL_UNORDERED_DENSE_HASH_STATICCAST(wchar_t);
412ANKERL_UNORDERED_DENSE_HASH_STATICCAST(short);
413ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned short);
414ANKERL_UNORDERED_DENSE_HASH_STATICCAST(int);
415ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned int);
416ANKERL_UNORDERED_DENSE_HASH_STATICCAST(long);
417ANKERL_UNORDERED_DENSE_HASH_STATICCAST(long long);
418ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned long);
419ANKERL_UNORDERED_DENSE_HASH_STATICCAST(unsigned long long);
420
421# if defined(__GNUC__) && !defined(__clang__)
422# pragma GCC diagnostic pop
423# endif
424
425// bucket_type //////////////////////////////////////////////////////////
426
427namespace bucket_type {
428
429struct standard {
430 static constexpr uint32_t dist_inc = 1U << 8U; // skip 1 byte fingerprint
431 static constexpr uint32_t fingerprint_mask = dist_inc - 1; // mask for 1 byte of fingerprint
432
433 uint32_t m_dist_and_fingerprint; // upper 3 byte: distance to original bucket. lower byte: fingerprint from hash
434 uint32_t m_value_idx; // index into the m_values vector.
435};
436
437ANKERL_UNORDERED_DENSE_PACK(struct big {
438 static constexpr uint32_t dist_inc = 1U << 8U; // skip 1 byte fingerprint
439 static constexpr uint32_t fingerprint_mask = dist_inc - 1; // mask for 1 byte of fingerprint
440
441 uint32_t m_dist_and_fingerprint; // upper 3 byte: distance to original bucket. lower byte: fingerprint from hash
442 size_t m_value_idx; // index into the m_values vector.
443});
444
445} // namespace bucket_type
446
447namespace detail {
448
449struct nonesuch {};
450struct default_container_t {};
451
452template <class Default, class AlwaysVoid, template <class...> class Op, class... Args>
453struct detector {
454 using value_t = std::false_type;
455 using type = Default;
456};
457
458template <class Default, template <class...> class Op, class... Args>
459struct detector<Default, std::void_t<Op<Args...>>, Op, Args...> {
460 using value_t = std::true_type;
461 using type = Op<Args...>;
462};
463
464template <template <class...> class Op, class... Args>
465using is_detected = typename detail::detector<detail::nonesuch, void, Op, Args...>::value_t;
466
467template <template <class...> class Op, class... Args>
468constexpr bool is_detected_v = is_detected<Op, Args...>::value;
469
470template <typename T>
471using detect_avalanching = typename T::is_avalanching;
472
473template <typename T>
474using detect_is_transparent = typename T::is_transparent;
475
476template <typename T>
477using detect_iterator = typename T::iterator;
478
479template <typename T>
480using detect_reserve = decltype(std::declval<T&>().reserve(size_t{}));
481
482// enable_if helpers
483
484template <typename Mapped>
485constexpr bool is_map_v = !std::is_void_v<Mapped>;
486
487// clang-format off
488template <typename Hash, typename KeyEqual>
489constexpr bool is_transparent_v = is_detected_v<detect_is_transparent, Hash> && is_detected_v<detect_is_transparent, KeyEqual>;
490// clang-format on
491
492template <typename From, typename To1, typename To2>
493constexpr bool is_neither_convertible_v = !std::is_convertible_v<From, To1> && !std::is_convertible_v<From, To2>;
494
495template <typename T>
496constexpr bool has_reserve = is_detected_v<detect_reserve, T>;
497
498// base type for map has mapped_type
499template <class T>
500struct base_table_type_map {
501 using mapped_type = T;
502};
503
504// base type for set doesn't have mapped_type
505struct base_table_type_set {};
506
507} // namespace detail
508
509// Very much like std::deque, but faster for indexing (in most cases). As of now this doesn't implement the full std::vector
510// API, but merely what's necessary to work as an underlying container for ankerl::unordered_dense::{map, set}.
511// It allocates blocks of equal size and puts them into the m_blocks vector. That means it can grow simply by adding a new
512// block to the back of m_blocks, and doesn't double its size like an std::vector. The disadvantage is that memory is not
513// linear and thus there is one more indirection necessary for indexing.
514template <typename T, typename Allocator = std::allocator<T>, size_t MaxSegmentSizeBytes = 4096>
515class segmented_vector {
516 template <bool IsConst>
517 class iter_t;
518
519public:
520 using allocator_type = Allocator;
521 using pointer = typename std::allocator_traits<allocator_type>::pointer;
522 using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer;
523 using difference_type = typename std::allocator_traits<allocator_type>::difference_type;
524 using value_type = T;
525 using size_type = size_t;
526 using reference = T&;
527 using const_reference = T const&;
528 using iterator = iter_t<false>;
529 using const_iterator = iter_t<true>;
530
531private:
532 using vec_alloc = typename std::allocator_traits<Allocator>::template rebind_alloc<pointer>;
533 std::vector<pointer, vec_alloc> m_blocks{};
534 size_t m_size{};
535
536 // Calculates the maximum number for x in (s << x) <= max_val
537 static constexpr auto num_bits_closest(size_t max_val, size_t s) -> size_t {
538 auto f = size_t{0};
539 while (s << (f + 1) <= max_val) {
540 ++f;
541 }
542 return f;
543 }
544
545 using self_t = segmented_vector<T, Allocator, MaxSegmentSizeBytes>;
546 static constexpr auto num_bits = num_bits_closest(MaxSegmentSizeBytes, sizeof(T));
547 static constexpr auto num_elements_in_block = 1U << num_bits;
548 static constexpr auto mask = num_elements_in_block - 1U;
549
553 template <bool IsConst>
554 class iter_t {
555 using ptr_t = typename std::conditional_t<IsConst, segmented_vector::const_pointer const*, segmented_vector::pointer*>;
556 ptr_t m_data{};
557 size_t m_idx{};
558
559 template <bool B>
560 friend class iter_t;
561
562 public:
563 using difference_type = segmented_vector::difference_type;
564 using value_type = T;
565 using reference = typename std::conditional_t<IsConst, value_type const&, value_type&>;
566 using pointer = typename std::conditional_t<IsConst, segmented_vector::const_pointer, segmented_vector::pointer>;
567 using iterator_category = std::forward_iterator_tag;
568
569 iter_t() noexcept = default;
570
571 template <bool OtherIsConst, typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
572 // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
573 constexpr iter_t(iter_t<OtherIsConst> const& other) noexcept
574 : m_data(other.m_data)
575 , m_idx(other.m_idx) {}
576
577 constexpr iter_t(ptr_t data, size_t idx) noexcept
578 : m_data(data)
579 , m_idx(idx) {}
580
581 template <bool OtherIsConst, typename = typename std::enable_if<IsConst && !OtherIsConst>::type>
582 constexpr auto operator=(iter_t<OtherIsConst> const& other) noexcept -> iter_t& {
583 m_data = other.m_data;
584 m_idx = other.m_idx;
585 return *this;
586 }
587
588 constexpr auto operator++() noexcept -> iter_t& {
589 ++m_idx;
590 return *this;
591 }
592
593 constexpr auto operator++(int) noexcept -> iter_t {
594 iter_t prev(*this);
595 this->operator++();
596 return prev;
597 }
598
599 constexpr auto operator+(difference_type diff) noexcept -> iter_t {
600 return {m_data, static_cast<size_t>(static_cast<difference_type>(m_idx) + diff)};
601 }
602
603 template <bool OtherIsConst>
604 constexpr auto operator-(iter_t<OtherIsConst> const& other) noexcept -> difference_type {
605 return static_cast<difference_type>(m_idx) - static_cast<difference_type>(other.m_idx);
606 }
607
608 constexpr auto operator*() const noexcept -> reference {
609 return m_data[m_idx >> num_bits][m_idx & mask];
610 }
611
612 constexpr auto operator->() const noexcept -> pointer {
613 return &m_data[m_idx >> num_bits][m_idx & mask];
614 }
615
616 template <bool O>
617 constexpr auto operator==(iter_t<O> const& o) const noexcept -> bool {
618 return m_idx == o.m_idx;
619 }
620
621 template <bool O>
622 constexpr auto operator!=(iter_t<O> const& o) const noexcept -> bool {
623 return !(*this == o);
624 }
625 };
626
627 // slow path: need to allocate a new segment every once in a while
628 void increase_capacity() {
629 auto ba = Allocator(m_blocks.get_allocator());
630 pointer block = std::allocator_traits<Allocator>::allocate(ba, num_elements_in_block);
631 m_blocks.push_back(block);
632 }
633
634 // Moves everything from other
635 void append_everything_from(segmented_vector&& other) {
636 reserve(size() + other.size());
637 for (auto&& o : other) {
638 emplace_back(std::move(o));
639 }
640 }
641
642 // Copies everything from other
643 void append_everything_from(segmented_vector const& other) {
644 reserve(size() + other.size());
645 for (auto const& o : other) {
646 emplace_back(o);
647 }
648 }
649
650 void dealloc() {
651 auto ba = Allocator(m_blocks.get_allocator());
652 for (auto ptr : m_blocks) {
653 std::allocator_traits<Allocator>::deallocate(ba, ptr, num_elements_in_block);
654 }
655 }
656
657 [[nodiscard]] static constexpr auto calc_num_blocks_for_capacity(size_t capacity) {
658 return (capacity + num_elements_in_block - 1U) / num_elements_in_block;
659 }
660
661public:
662 segmented_vector() = default;
663
664 // NOLINTNEXTLINE(google-explicit-constructor,hicpp-explicit-conversions)
665 segmented_vector(Allocator alloc)
666 : m_blocks(vec_alloc(alloc)) {}
667
668 segmented_vector(segmented_vector&& other, Allocator alloc)
669 : segmented_vector(alloc) {
670 *this = std::move(other);
671 }
672
673 segmented_vector(segmented_vector const& other, Allocator alloc)
674 : m_blocks(vec_alloc(alloc)) {
675 append_everything_from(other);
676 }
677
678 segmented_vector(segmented_vector&& other) noexcept
679 : segmented_vector(std::move(other), get_allocator()) {}
680
681 segmented_vector(segmented_vector const& other) {
682 append_everything_from(other);
683 }
684
685 auto operator=(segmented_vector const& other) -> segmented_vector& {
686 if (this == &other) {
687 return *this;
688 }
689 clear();
690 append_everything_from(other);
691 return *this;
692 }
693
694 auto operator=(segmented_vector&& other) noexcept -> segmented_vector& {
695 clear();
696 dealloc();
697 if (other.get_allocator() == get_allocator()) {
698 m_blocks = std::move(other.m_blocks);
699 m_size = std::exchange(other.m_size, {});
700 } else {
701 // make sure to construct with other's allocator!
702 m_blocks = std::vector<pointer, vec_alloc>(vec_alloc(other.get_allocator()));
703 append_everything_from(std::move(other));
704 }
705 return *this;
706 }
707
708 ~segmented_vector() {
709 clear();
710 dealloc();
711 }
712
713 [[nodiscard]] constexpr auto size() const -> size_t {
714 return m_size;
715 }
716
717 [[nodiscard]] constexpr auto capacity() const -> size_t {
718 return m_blocks.size() * num_elements_in_block;
719 }
720
721 // Indexing is highly performance critical
722 [[nodiscard]] constexpr auto operator[](size_t i) const noexcept -> T const& {
723 return m_blocks[i >> num_bits][i & mask];
724 }
725
726 [[nodiscard]] constexpr auto operator[](size_t i) noexcept -> T& {
727 return m_blocks[i >> num_bits][i & mask];
728 }
729
730 [[nodiscard]] constexpr auto begin() -> iterator {
731 return {m_blocks.data(), 0U};
732 }
733 [[nodiscard]] constexpr auto begin() const -> const_iterator {
734 return {m_blocks.data(), 0U};
735 }
736 [[nodiscard]] constexpr auto cbegin() const -> const_iterator {
737 return {m_blocks.data(), 0U};
738 }
739
740 [[nodiscard]] constexpr auto end() -> iterator {
741 return {m_blocks.data(), m_size};
742 }
743 [[nodiscard]] constexpr auto end() const -> const_iterator {
744 return {m_blocks.data(), m_size};
745 }
746 [[nodiscard]] constexpr auto cend() const -> const_iterator {
747 return {m_blocks.data(), m_size};
748 }
749
750 [[nodiscard]] constexpr auto back() -> reference {
751 return operator[](m_size - 1);
752 }
753 [[nodiscard]] constexpr auto back() const -> const_reference {
754 return operator[](m_size - 1);
755 }
756
757 void pop_back() {
758 back().~T();
759 --m_size;
760 }
761
762 [[nodiscard]] auto empty() const {
763 return 0 == m_size;
764 }
765
766 void reserve(size_t new_capacity) {
767 m_blocks.reserve(calc_num_blocks_for_capacity(new_capacity));
768 while (new_capacity > capacity()) {
769 increase_capacity();
770 }
771 }
772
773 [[nodiscard]] auto get_allocator() const -> allocator_type {
774 return allocator_type{m_blocks.get_allocator()};
775 }
776
777 template <class... Args>
778 auto emplace_back(Args&&... args) -> reference {
779 if (m_size == capacity()) {
780 increase_capacity();
781 }
782 auto* ptr = static_cast<void*>(&operator[](m_size));
783 auto& ref = *new (ptr) T(std::forward<Args>(args)...);
784 ++m_size;
785 return ref;
786 }
787
788 void clear() {
789 if constexpr (!std::is_trivially_destructible_v<T>) {
790 for (size_t i = 0, s = size(); i < s; ++i) {
791 operator[](i).~T();
792 }
793 }
794 m_size = 0;
795 }
796
797 void shrink_to_fit() {
798 auto ba = Allocator(m_blocks.get_allocator());
799 auto num_blocks_required = calc_num_blocks_for_capacity(m_size);
800 while (m_blocks.size() > num_blocks_required) {
801 std::allocator_traits<Allocator>::deallocate(ba, m_blocks.back(), num_elements_in_block);
802 m_blocks.pop_back();
803 }
804 m_blocks.shrink_to_fit();
805 }
806};
807
808namespace detail {
809
810// This is it, the table. Doubles as map and set, and uses `void` for T when its used as a set.
811template <class Key,
812 class T, // when void, treat it as a set.
813 class Hash,
814 class KeyEqual,
815 class AllocatorOrContainer,
816 class Bucket,
817 class BucketContainer,
818 bool IsSegmented>
819class table : public std::conditional_t<is_map_v<T>, base_table_type_map<T>, base_table_type_set> {
820 using underlying_value_type = typename std::conditional_t<is_map_v<T>, std::pair<Key, T>, Key>;
821 using underlying_container_type = std::conditional_t<IsSegmented,
822 segmented_vector<underlying_value_type, AllocatorOrContainer>,
823 std::vector<underlying_value_type, AllocatorOrContainer>>;
824
825public:
826 using value_container_type = std::
827 conditional_t<is_detected_v<detect_iterator, AllocatorOrContainer>, AllocatorOrContainer, underlying_container_type>;
828
829private:
830 using bucket_alloc =
831 typename std::allocator_traits<typename value_container_type::allocator_type>::template rebind_alloc<Bucket>;
832 using default_bucket_container_type =
833 std::conditional_t<IsSegmented, segmented_vector<Bucket, bucket_alloc>, std::vector<Bucket, bucket_alloc>>;
834
835 using bucket_container_type = std::conditional_t<std::is_same_v<BucketContainer, detail::default_container_t>,
836 default_bucket_container_type,
837 BucketContainer>;
838
839 static constexpr uint8_t initial_shifts = 64 - 2; // 2^(64-m_shift) number of buckets
840 static constexpr float default_max_load_factor = 0.8F;
841
842public:
843 using key_type = Key;
844 using value_type = typename value_container_type::value_type;
845 using size_type = typename value_container_type::size_type;
846 using difference_type = typename value_container_type::difference_type;
847 using hasher = Hash;
848 using key_equal = KeyEqual;
849 using allocator_type = typename value_container_type::allocator_type;
850 using reference = typename value_container_type::reference;
851 using const_reference = typename value_container_type::const_reference;
852 using pointer = typename value_container_type::pointer;
853 using const_pointer = typename value_container_type::const_pointer;
854 using const_iterator = typename value_container_type::const_iterator;
855 using iterator = std::conditional_t<is_map_v<T>, typename value_container_type::iterator, const_iterator>;
856 using bucket_type = Bucket;
857
858private:
859 using value_idx_type = decltype(Bucket::m_value_idx);
860 using dist_and_fingerprint_type = decltype(Bucket::m_dist_and_fingerprint);
861
862 static_assert(std::is_trivially_destructible_v<Bucket>, "assert there's no need to call destructor / std::destroy");
863 static_assert(std::is_trivially_copyable_v<Bucket>, "assert we can just memset / memcpy");
864
865 value_container_type m_values{}; // Contains all the key-value pairs in one densely stored container. No holes.
866 bucket_container_type m_buckets{};
867 size_t m_max_bucket_capacity = 0;
868 float m_max_load_factor = default_max_load_factor;
869 Hash m_hash{};
870 KeyEqual m_equal{};
871 uint8_t m_shifts = initial_shifts;
872
873 [[nodiscard]] auto next(value_idx_type bucket_idx) const -> value_idx_type {
874 return ANKERL_UNORDERED_DENSE_UNLIKELY(bucket_idx + 1U == bucket_count())
875 ? 0
876 : static_cast<value_idx_type>(bucket_idx + 1U);
877 }
878
879 // Helper to access bucket through pointer types
880 [[nodiscard]] static constexpr auto at(bucket_container_type& bucket, size_t offset) -> Bucket& {
881 return bucket[offset];
882 }
883
884 [[nodiscard]] static constexpr auto at(const bucket_container_type& bucket, size_t offset) -> const Bucket& {
885 return bucket[offset];
886 }
887
888 // use the dist_inc and dist_dec functions so that uint16_t types work without warning
889 [[nodiscard]] static constexpr auto dist_inc(dist_and_fingerprint_type x) -> dist_and_fingerprint_type {
890 return static_cast<dist_and_fingerprint_type>(x + Bucket::dist_inc);
891 }
892
893 [[nodiscard]] static constexpr auto dist_dec(dist_and_fingerprint_type x) -> dist_and_fingerprint_type {
894 return static_cast<dist_and_fingerprint_type>(x - Bucket::dist_inc);
895 }
896
897 // The goal of mixed_hash is to always produce a high quality 64bit hash.
898 template <typename K>
899 [[nodiscard]] constexpr auto mixed_hash(K const& key) const -> uint64_t {
900 if constexpr (is_detected_v<detect_avalanching, Hash>) {
901 // we know that the hash is good because is_avalanching.
902 if constexpr (sizeof(decltype(m_hash(key))) < sizeof(uint64_t)) {
903 // 32bit hash and is_avalanching => multiply with a constant to avalanche bits upwards
904 return m_hash(key) * UINT64_C(0x9ddfea08eb382d69);
905 } else {
906 // 64bit and is_avalanching => only use the hash itself.
907 return m_hash(key);
908 }
909 } else {
910 // not is_avalanching => apply wyhash
911 return wyhash::hash(m_hash(key));
912 }
913 }
914
915 [[nodiscard]] constexpr auto dist_and_fingerprint_from_hash(uint64_t hash) const -> dist_and_fingerprint_type {
916 return Bucket::dist_inc | (static_cast<dist_and_fingerprint_type>(hash) & Bucket::fingerprint_mask);
917 }
918
919 [[nodiscard]] constexpr auto bucket_idx_from_hash(uint64_t hash) const -> value_idx_type {
920 return static_cast<value_idx_type>(hash >> m_shifts);
921 }
922
923 [[nodiscard]] static constexpr auto get_key(value_type const& vt) -> key_type const& {
924 if constexpr (is_map_v<T>) {
925 return vt.first;
926 } else {
927 return vt;
928 }
929 }
930
931 template <typename K>
932 [[nodiscard]] auto next_while_less(K const& key) const -> Bucket {
933 auto hash = mixed_hash(key);
934 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
935 auto bucket_idx = bucket_idx_from_hash(hash);
936
937 while (dist_and_fingerprint < at(m_buckets, bucket_idx).m_dist_and_fingerprint) {
938 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
939 bucket_idx = next(bucket_idx);
940 }
941 return {dist_and_fingerprint, bucket_idx};
942 }
943
944 void place_and_shift_up(Bucket bucket, value_idx_type place) {
945 while (0 != at(m_buckets, place).m_dist_and_fingerprint) {
946 bucket = std::exchange(at(m_buckets, place), bucket);
947 bucket.m_dist_and_fingerprint = dist_inc(bucket.m_dist_and_fingerprint);
948 place = next(place);
949 }
950 at(m_buckets, place) = bucket;
951 }
952
953 [[nodiscard]] static constexpr auto calc_num_buckets(uint8_t shifts) -> size_t {
954 return (std::min)(max_bucket_count(), size_t{1} << (64U - shifts));
955 }
956
957 [[nodiscard]] constexpr auto calc_shifts_for_size(size_t s) const -> uint8_t {
958 auto shifts = initial_shifts;
959 while (shifts > 0 && static_cast<size_t>(static_cast<float>(calc_num_buckets(shifts)) * max_load_factor()) < s) {
960 --shifts;
961 }
962 return shifts;
963 }
964
965 // assumes m_values has data, m_buckets=m_buckets_end=nullptr, m_shifts is INITIAL_SHIFTS
966 void copy_buckets(table const& other) {
967 // assumes m_values has already the correct data copied over.
968 if (empty()) {
969 // when empty, at least allocate an initial buckets and clear them.
970 allocate_buckets_from_shift();
971 clear_buckets();
972 } else {
973 m_shifts = other.m_shifts;
974 allocate_buckets_from_shift();
975 if constexpr (IsSegmented || !std::is_same_v<BucketContainer, default_container_t>) {
976 for (auto i = 0UL; i < bucket_count(); ++i) {
977 at(m_buckets, i) = at(other.m_buckets, i);
978 }
979 } else {
980 std::memcpy(m_buckets.data(), other.m_buckets.data(), sizeof(Bucket) * bucket_count());
981 }
982 }
983 }
984
988 [[nodiscard]] auto is_full() const -> bool {
989 return size() > m_max_bucket_capacity;
990 }
991
992 void deallocate_buckets() {
993 m_buckets.clear();
994 m_buckets.shrink_to_fit();
995 m_max_bucket_capacity = 0;
996 }
997
998 void allocate_buckets_from_shift() {
999 auto num_buckets = calc_num_buckets(m_shifts);
1000 if constexpr (IsSegmented || !std::is_same_v<BucketContainer, default_container_t>) {
1001 if constexpr (has_reserve<bucket_container_type>) {
1002 m_buckets.reserve(num_buckets);
1003 }
1004 for (size_t i = m_buckets.size(); i < num_buckets; ++i) {
1005 m_buckets.emplace_back();
1006 }
1007 } else {
1008 m_buckets.resize(num_buckets);
1009 }
1010 if (num_buckets == max_bucket_count()) {
1011 // reached the maximum, make sure we can use each bucket
1012 m_max_bucket_capacity = max_bucket_count();
1013 } else {
1014 m_max_bucket_capacity = static_cast<value_idx_type>(static_cast<float>(num_buckets) * max_load_factor());
1015 }
1016 }
1017
1018 void clear_buckets() {
1019 if constexpr (IsSegmented || !std::is_same_v<BucketContainer, default_container_t>) {
1020 for (auto&& e : m_buckets) {
1021 std::memset(&e, 0, sizeof(e));
1022 }
1023 } else {
1024 std::memset(m_buckets.data(), 0, sizeof(Bucket) * bucket_count());
1025 }
1026 }
1027
1028 void clear_and_fill_buckets_from_values() {
1029 clear_buckets();
1030 for (value_idx_type value_idx = 0, end_idx = static_cast<value_idx_type>(m_values.size()); value_idx < end_idx;
1031 ++value_idx) {
1032 auto const& key = get_key(m_values[value_idx]);
1033 auto [dist_and_fingerprint, bucket] = next_while_less(key);
1034
1035 // we know for certain that key has not yet been inserted, so no need to check it.
1036 place_and_shift_up({dist_and_fingerprint, value_idx}, bucket);
1037 }
1038 }
1039
1040 void increase_size() {
1041 if (m_max_bucket_capacity == max_bucket_count()) {
1042 // remove the value again, we can't add it!
1043 m_values.pop_back();
1044 on_error_bucket_overflow();
1045 }
1046 --m_shifts;
1047 if constexpr (!IsSegmented || std::is_same_v<BucketContainer, default_container_t>) {
1048 deallocate_buckets();
1049 }
1050 allocate_buckets_from_shift();
1051 clear_and_fill_buckets_from_values();
1052 }
1053
1054 template <typename Op>
1055 void do_erase(value_idx_type bucket_idx, Op handle_erased_value) {
1056 auto const value_idx_to_remove = at(m_buckets, bucket_idx).m_value_idx;
1057
1058 // shift down until either empty or an element with correct spot is found
1059 auto next_bucket_idx = next(bucket_idx);
1060 while (at(m_buckets, next_bucket_idx).m_dist_and_fingerprint >= Bucket::dist_inc * 2) {
1061 at(m_buckets, bucket_idx) = {dist_dec(at(m_buckets, next_bucket_idx).m_dist_and_fingerprint),
1062 at(m_buckets, next_bucket_idx).m_value_idx};
1063 bucket_idx = std::exchange(next_bucket_idx, next(next_bucket_idx));
1064 }
1065 at(m_buckets, bucket_idx) = {};
1066 handle_erased_value(std::move(m_values[value_idx_to_remove]));
1067
1068 // update m_values
1069 if (value_idx_to_remove != m_values.size() - 1) {
1070 // no luck, we'll have to replace the value with the last one and update the index accordingly
1071 auto& val = m_values[value_idx_to_remove];
1072 val = std::move(m_values.back());
1073
1074 // update the values_idx of the moved entry. No need to play the info game, just look until we find the values_idx
1075 auto mh = mixed_hash(get_key(val));
1076 bucket_idx = bucket_idx_from_hash(mh);
1077
1078 auto const values_idx_back = static_cast<value_idx_type>(m_values.size() - 1);
1079 while (values_idx_back != at(m_buckets, bucket_idx).m_value_idx) {
1080 bucket_idx = next(bucket_idx);
1081 }
1082 at(m_buckets, bucket_idx).m_value_idx = value_idx_to_remove;
1083 }
1084 m_values.pop_back();
1085 }
1086
1087 template <typename K, typename Op>
1088 auto do_erase_key(K&& key, Op handle_erased_value) -> size_t {
1089 if (empty()) {
1090 return 0;
1091 }
1092
1093 auto [dist_and_fingerprint, bucket_idx] = next_while_less(key);
1094
1095 while (dist_and_fingerprint == at(m_buckets, bucket_idx).m_dist_and_fingerprint &&
1096 !m_equal(key, get_key(m_values[at(m_buckets, bucket_idx).m_value_idx]))) {
1097 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1098 bucket_idx = next(bucket_idx);
1099 }
1100
1101 if (dist_and_fingerprint != at(m_buckets, bucket_idx).m_dist_and_fingerprint) {
1102 return 0;
1103 }
1104 do_erase(bucket_idx, handle_erased_value);
1105 return 1;
1106 }
1107
1108 template <class K, class M>
1109 auto do_insert_or_assign(K&& key, M&& mapped) -> std::pair<iterator, bool> {
1110 auto it_isinserted = try_emplace(std::forward<K>(key), std::forward<M>(mapped));
1111 if (!it_isinserted.second) {
1112 it_isinserted.first->second = std::forward<M>(mapped);
1113 }
1114 return it_isinserted;
1115 }
1116
1117 template <typename... Args>
1118 auto do_place_element(dist_and_fingerprint_type dist_and_fingerprint, value_idx_type bucket_idx, Args&&... args)
1119 -> std::pair<iterator, bool> {
1120
1121 // emplace the new value. If that throws an exception, no harm done; index is still in a valid state
1122 m_values.emplace_back(std::forward<Args>(args)...);
1123
1124 auto value_idx = static_cast<value_idx_type>(m_values.size() - 1);
1125 if (ANKERL_UNORDERED_DENSE_UNLIKELY(is_full())) {
1126 increase_size();
1127 } else {
1128 place_and_shift_up({dist_and_fingerprint, value_idx}, bucket_idx);
1129 }
1130
1131 // place element and shift up until we find an empty spot
1132 return {begin() + static_cast<difference_type>(value_idx), true};
1133 }
1134
1135 template <typename K, typename... Args>
1136 auto do_try_emplace(K&& key, Args&&... args) -> std::pair<iterator, bool> {
1137 auto hash = mixed_hash(key);
1138 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
1139 auto bucket_idx = bucket_idx_from_hash(hash);
1140
1141 while (true) {
1142 auto* bucket = &at(m_buckets, bucket_idx);
1143 if (dist_and_fingerprint == bucket->m_dist_and_fingerprint) {
1144 if (m_equal(key, get_key(m_values[bucket->m_value_idx]))) {
1145 return {begin() + static_cast<difference_type>(bucket->m_value_idx), false};
1146 }
1147 } else if (dist_and_fingerprint > bucket->m_dist_and_fingerprint) {
1148 return do_place_element(dist_and_fingerprint,
1149 bucket_idx,
1150 std::piecewise_construct,
1151 std::forward_as_tuple(std::forward<K>(key)),
1152 std::forward_as_tuple(std::forward<Args>(args)...));
1153 }
1154 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1155 bucket_idx = next(bucket_idx);
1156 }
1157 }
1158
1159 template <typename K>
1160 auto do_find(K const& key) -> iterator {
1161 if (ANKERL_UNORDERED_DENSE_UNLIKELY(empty())) {
1162 return end();
1163 }
1164
1165 auto mh = mixed_hash(key);
1166 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(mh);
1167 auto bucket_idx = bucket_idx_from_hash(mh);
1168 auto* bucket = &at(m_buckets, bucket_idx);
1169
1170 // unrolled loop. *Always* check a few directly, then enter the loop. This is faster.
1171 if (dist_and_fingerprint == bucket->m_dist_and_fingerprint && m_equal(key, get_key(m_values[bucket->m_value_idx]))) {
1172 return begin() + static_cast<difference_type>(bucket->m_value_idx);
1173 }
1174 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1175 bucket_idx = next(bucket_idx);
1176 bucket = &at(m_buckets, bucket_idx);
1177
1178 if (dist_and_fingerprint == bucket->m_dist_and_fingerprint && m_equal(key, get_key(m_values[bucket->m_value_idx]))) {
1179 return begin() + static_cast<difference_type>(bucket->m_value_idx);
1180 }
1181 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1182 bucket_idx = next(bucket_idx);
1183 bucket = &at(m_buckets, bucket_idx);
1184
1185 while (true) {
1186 if (dist_and_fingerprint == bucket->m_dist_and_fingerprint) {
1187 if (m_equal(key, get_key(m_values[bucket->m_value_idx]))) {
1188 return begin() + static_cast<difference_type>(bucket->m_value_idx);
1189 }
1190 } else if (dist_and_fingerprint > bucket->m_dist_and_fingerprint) {
1191 return end();
1192 }
1193 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1194 bucket_idx = next(bucket_idx);
1195 bucket = &at(m_buckets, bucket_idx);
1196 }
1197 }
1198
1199 template <typename K>
1200 auto do_find(K const& key) const -> const_iterator {
1201 return const_cast<table*>(this)->do_find(key); // NOLINT(cppcoreguidelines-pro-type-const-cast)
1202 }
1203
1204 template <typename K, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1205 auto do_at(K const& key) -> Q& {
1206 if (auto it = find(key); ANKERL_UNORDERED_DENSE_LIKELY(end() != it)) {
1207 return it->second;
1208 }
1209 on_error_key_not_found();
1210 }
1211
1212 template <typename K, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1213 auto do_at(K const& key) const -> Q const& {
1214 return const_cast<table*>(this)->at(key); // NOLINT(cppcoreguidelines-pro-type-const-cast)
1215 }
1216
1217public:
1218 explicit table(size_t bucket_count,
1219 Hash const& hash = Hash(),
1220 KeyEqual const& equal = KeyEqual(),
1221 allocator_type const& alloc_or_container = allocator_type())
1222 : m_values(alloc_or_container)
1223 , m_buckets(alloc_or_container)
1224 , m_hash(hash)
1225 , m_equal(equal) {
1226 if (0 != bucket_count) {
1227 reserve(bucket_count);
1228 } else {
1229 allocate_buckets_from_shift();
1230 clear_buckets();
1231 }
1232 }
1233
1234 table()
1235 : table(0) {}
1236
1237 table(size_t bucket_count, allocator_type const& alloc)
1238 : table(bucket_count, Hash(), KeyEqual(), alloc) {}
1239
1240 table(size_t bucket_count, Hash const& hash, allocator_type const& alloc)
1241 : table(bucket_count, hash, KeyEqual(), alloc) {}
1242
1243 explicit table(allocator_type const& alloc)
1244 : table(0, Hash(), KeyEqual(), alloc) {}
1245
1246 template <class InputIt>
1247 table(InputIt first,
1248 InputIt last,
1249 size_type bucket_count = 0,
1250 Hash const& hash = Hash(),
1251 KeyEqual const& equal = KeyEqual(),
1252 allocator_type const& alloc = allocator_type())
1253 : table(bucket_count, hash, equal, alloc) {
1254 insert(first, last);
1255 }
1256
1257 template <class InputIt>
1258 table(InputIt first, InputIt last, size_type bucket_count, allocator_type const& alloc)
1259 : table(first, last, bucket_count, Hash(), KeyEqual(), alloc) {}
1260
1261 template <class InputIt>
1262 table(InputIt first, InputIt last, size_type bucket_count, Hash const& hash, allocator_type const& alloc)
1263 : table(first, last, bucket_count, hash, KeyEqual(), alloc) {}
1264
1265 table(table const& other)
1266 : table(other, other.m_values.get_allocator()) {}
1267
1268 table(table const& other, allocator_type const& alloc)
1269 : m_values(other.m_values, alloc)
1270 , m_max_load_factor(other.m_max_load_factor)
1271 , m_hash(other.m_hash)
1272 , m_equal(other.m_equal) {
1273 copy_buckets(other);
1274 }
1275
1276 table(table&& other) noexcept
1277 : table(std::move(other), other.m_values.get_allocator()) {}
1278
1279 table(table&& other, allocator_type const& alloc) noexcept
1280 : m_values(alloc) {
1281 *this = std::move(other);
1282 }
1283
1284 table(std::initializer_list<value_type> ilist,
1285 size_t bucket_count = 0,
1286 Hash const& hash = Hash(),
1287 KeyEqual const& equal = KeyEqual(),
1288 allocator_type const& alloc = allocator_type())
1289 : table(bucket_count, hash, equal, alloc) {
1290 insert(ilist);
1291 }
1292
1293 table(std::initializer_list<value_type> ilist, size_type bucket_count, allocator_type const& alloc)
1294 : table(ilist, bucket_count, Hash(), KeyEqual(), alloc) {}
1295
1296 table(std::initializer_list<value_type> init, size_type bucket_count, Hash const& hash, allocator_type const& alloc)
1297 : table(init, bucket_count, hash, KeyEqual(), alloc) {}
1298
1299 ~table() {}
1300
1301 auto operator=(table const& other) -> table& {
1302 if (&other != this) {
1303 deallocate_buckets(); // deallocate before m_values is set (might have another allocator)
1304 m_values = other.m_values;
1305 m_max_load_factor = other.m_max_load_factor;
1306 m_hash = other.m_hash;
1307 m_equal = other.m_equal;
1308 m_shifts = initial_shifts;
1309 copy_buckets(other);
1310 }
1311 return *this;
1312 }
1313
1314 auto operator=(table&& other) noexcept(noexcept(std::is_nothrow_move_assignable_v<value_container_type> &&
1315 std::is_nothrow_move_assignable_v<Hash> &&
1316 std::is_nothrow_move_assignable_v<KeyEqual>)) -> table& {
1317 if (&other != this) {
1318 deallocate_buckets(); // deallocate before m_values is set (might have another allocator)
1319 m_values = std::move(other.m_values);
1320 other.m_values.clear();
1321
1322 // we can only reuse m_buckets when both maps have the same allocator!
1323 if (get_allocator() == other.get_allocator()) {
1324 m_buckets = std::move(other.m_buckets);
1325 other.m_buckets.clear();
1326 m_max_bucket_capacity = std::exchange(other.m_max_bucket_capacity, 0);
1327 m_shifts = std::exchange(other.m_shifts, initial_shifts);
1328 m_max_load_factor = std::exchange(other.m_max_load_factor, default_max_load_factor);
1329 m_hash = std::exchange(other.m_hash, {});
1330 m_equal = std::exchange(other.m_equal, {});
1331 other.allocate_buckets_from_shift();
1332 other.clear_buckets();
1333 } else {
1334 // set max_load_factor *before* copying the other's buckets, so we have the same
1335 // behavior
1336 m_max_load_factor = other.m_max_load_factor;
1337
1338 // copy_buckets sets m_buckets, m_num_buckets, m_max_bucket_capacity, m_shifts
1339 copy_buckets(other);
1340 // clear's the other's buckets so other is now already usable.
1341 other.clear_buckets();
1342 m_hash = other.m_hash;
1343 m_equal = other.m_equal;
1344 }
1345 // map "other" is now already usable, it's empty.
1346 }
1347 return *this;
1348 }
1349
1350 auto operator=(std::initializer_list<value_type> ilist) -> table& {
1351 clear();
1352 insert(ilist);
1353 return *this;
1354 }
1355
1356 auto get_allocator() const noexcept -> allocator_type {
1357 return m_values.get_allocator();
1358 }
1359
1360 // iterators //////////////////////////////////////////////////////////////
1361
1362 auto begin() noexcept -> iterator {
1363 return m_values.begin();
1364 }
1365
1366 auto begin() const noexcept -> const_iterator {
1367 return m_values.begin();
1368 }
1369
1370 auto cbegin() const noexcept -> const_iterator {
1371 return m_values.cbegin();
1372 }
1373
1374 auto end() noexcept -> iterator {
1375 return m_values.end();
1376 }
1377
1378 auto cend() const noexcept -> const_iterator {
1379 return m_values.cend();
1380 }
1381
1382 auto end() const noexcept -> const_iterator {
1383 return m_values.end();
1384 }
1385
1386 // capacity ///////////////////////////////////////////////////////////////
1387
1388 [[nodiscard]] auto empty() const noexcept -> bool {
1389 return m_values.empty();
1390 }
1391
1392 [[nodiscard]] auto size() const noexcept -> size_t {
1393 return m_values.size();
1394 }
1395
1396 [[nodiscard]] static constexpr auto max_size() noexcept -> size_t {
1397 if constexpr ((std::numeric_limits<value_idx_type>::max)() == (std::numeric_limits<size_t>::max)()) {
1398 return size_t{1} << (sizeof(value_idx_type) * 8 - 1);
1399 } else {
1400 return size_t{1} << (sizeof(value_idx_type) * 8);
1401 }
1402 }
1403
1404 // modifiers //////////////////////////////////////////////////////////////
1405
1406 void clear() {
1407 m_values.clear();
1408 clear_buckets();
1409 }
1410
1411 auto insert(value_type const& value) -> std::pair<iterator, bool> {
1412 return emplace(value);
1413 }
1414
1415 auto insert(value_type&& value) -> std::pair<iterator, bool> {
1416 return emplace(std::move(value));
1417 }
1418
1419 template <class P, std::enable_if_t<std::is_constructible_v<value_type, P&&>, bool> = true>
1420 auto insert(P&& value) -> std::pair<iterator, bool> {
1421 return emplace(std::forward<P>(value));
1422 }
1423
1424 auto insert(const_iterator /*hint*/, value_type const& value) -> iterator {
1425 return insert(value).first;
1426 }
1427
1428 auto insert(const_iterator /*hint*/, value_type&& value) -> iterator {
1429 return insert(std::move(value)).first;
1430 }
1431
1432 template <class P, std::enable_if_t<std::is_constructible_v<value_type, P&&>, bool> = true>
1433 auto insert(const_iterator /*hint*/, P&& value) -> iterator {
1434 return insert(std::forward<P>(value)).first;
1435 }
1436
1437 template <class InputIt>
1438 void insert(InputIt first, InputIt last) {
1439 while (first != last) {
1440 insert(*first);
1441 ++first;
1442 }
1443 }
1444
1445 void insert(std::initializer_list<value_type> ilist) {
1446 insert(ilist.begin(), ilist.end());
1447 }
1448
1449 // nonstandard API: *this is emptied.
1450 // Also see "A Standard flat_map" https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2022/p0429r9.pdf
1451 auto extract() && -> value_container_type {
1452 return std::move(m_values);
1453 }
1454
1455 // nonstandard API:
1456 // Discards the internally held container and replaces it with the one passed. Erases non-unique elements.
1457 auto replace(value_container_type&& container) {
1458 if (ANKERL_UNORDERED_DENSE_UNLIKELY(container.size() > max_size())) {
1459 on_error_too_many_elements();
1460 }
1461 auto shifts = calc_shifts_for_size(container.size());
1462 if (0 == bucket_count() || shifts < m_shifts || container.get_allocator() != m_values.get_allocator()) {
1463 m_shifts = shifts;
1464 deallocate_buckets();
1465 allocate_buckets_from_shift();
1466 }
1467 clear_buckets();
1468
1469 m_values = std::move(container);
1470
1471 // can't use clear_and_fill_buckets_from_values() because container elements might not be unique
1472 auto value_idx = value_idx_type{};
1473
1474 // loop until we reach the end of the container. duplicated entries will be replaced with back().
1475 while (value_idx != static_cast<value_idx_type>(m_values.size())) {
1476 auto const& key = get_key(m_values[value_idx]);
1477
1478 auto hash = mixed_hash(key);
1479 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
1480 auto bucket_idx = bucket_idx_from_hash(hash);
1481
1482 bool key_found = false;
1483 while (true) {
1484 auto const& bucket = at(m_buckets, bucket_idx);
1485 if (dist_and_fingerprint > bucket.m_dist_and_fingerprint) {
1486 break;
1487 }
1488 if (dist_and_fingerprint == bucket.m_dist_and_fingerprint &&
1489 m_equal(key, get_key(m_values[bucket.m_value_idx]))) {
1490 key_found = true;
1491 break;
1492 }
1493 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1494 bucket_idx = next(bucket_idx);
1495 }
1496
1497 if (key_found) {
1498 if (value_idx != static_cast<value_idx_type>(m_values.size() - 1)) {
1499 m_values[value_idx] = std::move(m_values.back());
1500 }
1501 m_values.pop_back();
1502 } else {
1503 place_and_shift_up({dist_and_fingerprint, value_idx}, bucket_idx);
1504 ++value_idx;
1505 }
1506 }
1507 }
1508
1509 template <class M, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1510 auto insert_or_assign(Key const& key, M&& mapped) -> std::pair<iterator, bool> {
1511 return do_insert_or_assign(key, std::forward<M>(mapped));
1512 }
1513
1514 template <class M, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1515 auto insert_or_assign(Key&& key, M&& mapped) -> std::pair<iterator, bool> {
1516 return do_insert_or_assign(std::move(key), std::forward<M>(mapped));
1517 }
1518
1519 template <typename K,
1520 typename M,
1521 typename Q = T,
1522 typename H = Hash,
1523 typename KE = KeyEqual,
1524 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1525 auto insert_or_assign(K&& key, M&& mapped) -> std::pair<iterator, bool> {
1526 return do_insert_or_assign(std::forward<K>(key), std::forward<M>(mapped));
1527 }
1528
1529 template <class M, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1530 auto insert_or_assign(const_iterator /*hint*/, Key const& key, M&& mapped) -> iterator {
1531 return do_insert_or_assign(key, std::forward<M>(mapped)).first;
1532 }
1533
1534 template <class M, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1535 auto insert_or_assign(const_iterator /*hint*/, Key&& key, M&& mapped) -> iterator {
1536 return do_insert_or_assign(std::move(key), std::forward<M>(mapped)).first;
1537 }
1538
1539 template <typename K,
1540 typename M,
1541 typename Q = T,
1542 typename H = Hash,
1543 typename KE = KeyEqual,
1544 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1545 auto insert_or_assign(const_iterator /*hint*/, K&& key, M&& mapped) -> iterator {
1546 return do_insert_or_assign(std::forward<K>(key), std::forward<M>(mapped)).first;
1547 }
1548
1549 // Single arguments for unordered_set can be used without having to construct the value_type
1550 template <class K,
1551 typename Q = T,
1552 typename H = Hash,
1553 typename KE = KeyEqual,
1554 std::enable_if_t<!is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1555 auto emplace(K&& key) -> std::pair<iterator, bool> {
1556 auto hash = mixed_hash(key);
1557 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
1558 auto bucket_idx = bucket_idx_from_hash(hash);
1559
1560 while (dist_and_fingerprint <= at(m_buckets, bucket_idx).m_dist_and_fingerprint) {
1561 if (dist_and_fingerprint == at(m_buckets, bucket_idx).m_dist_and_fingerprint &&
1562 m_equal(key, m_values[at(m_buckets, bucket_idx).m_value_idx])) {
1563 // found it, return without ever actually creating anything
1564 return {begin() + static_cast<difference_type>(at(m_buckets, bucket_idx).m_value_idx), false};
1565 }
1566 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1567 bucket_idx = next(bucket_idx);
1568 }
1569
1570 // value is new, insert element first, so when exception happens we are in a valid state
1571 return do_place_element(dist_and_fingerprint, bucket_idx, std::forward<K>(key));
1572 }
1573
1574 template <class... Args>
1575 auto emplace(Args&&... args) -> std::pair<iterator, bool> {
1576 // we have to instantiate the value_type to be able to access the key.
1577 // 1. emplace_back the object so it is constructed. 2. If the key is already there, pop it later in the loop.
1578 auto& key = get_key(m_values.emplace_back(std::forward<Args>(args)...));
1579 auto hash = mixed_hash(key);
1580 auto dist_and_fingerprint = dist_and_fingerprint_from_hash(hash);
1581 auto bucket_idx = bucket_idx_from_hash(hash);
1582
1583 while (dist_and_fingerprint <= at(m_buckets, bucket_idx).m_dist_and_fingerprint) {
1584 if (dist_and_fingerprint == at(m_buckets, bucket_idx).m_dist_and_fingerprint &&
1585 m_equal(key, get_key(m_values[at(m_buckets, bucket_idx).m_value_idx]))) {
1586 m_values.pop_back(); // value was already there, so get rid of it
1587 return {begin() + static_cast<difference_type>(at(m_buckets, bucket_idx).m_value_idx), false};
1588 }
1589 dist_and_fingerprint = dist_inc(dist_and_fingerprint);
1590 bucket_idx = next(bucket_idx);
1591 }
1592
1593 // value is new, place the bucket and shift up until we find an empty spot
1594 auto value_idx = static_cast<value_idx_type>(m_values.size() - 1);
1595 if (ANKERL_UNORDERED_DENSE_UNLIKELY(is_full())) {
1596 // increase_size just rehashes all the data we have in m_values
1597 increase_size();
1598 } else {
1599 // place element and shift up until we find an empty spot
1600 place_and_shift_up({dist_and_fingerprint, value_idx}, bucket_idx);
1601 }
1602 return {begin() + static_cast<difference_type>(value_idx), true};
1603 }
1604
1605 template <class... Args>
1606 auto emplace_hint(const_iterator /*hint*/, Args&&... args) -> iterator {
1607 return emplace(std::forward<Args>(args)...).first;
1608 }
1609
1610 template <class... Args, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1611 auto try_emplace(Key const& key, Args&&... args) -> std::pair<iterator, bool> {
1612 return do_try_emplace(key, std::forward<Args>(args)...);
1613 }
1614
1615 template <class... Args, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1616 auto try_emplace(Key&& key, Args&&... args) -> std::pair<iterator, bool> {
1617 return do_try_emplace(std::move(key), std::forward<Args>(args)...);
1618 }
1619
1620 template <class... Args, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1621 auto try_emplace(const_iterator /*hint*/, Key const& key, Args&&... args) -> iterator {
1622 return do_try_emplace(key, std::forward<Args>(args)...).first;
1623 }
1624
1625 template <class... Args, typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1626 auto try_emplace(const_iterator /*hint*/, Key&& key, Args&&... args) -> iterator {
1627 return do_try_emplace(std::move(key), std::forward<Args>(args)...).first;
1628 }
1629
1630 template <
1631 typename K,
1632 typename... Args,
1633 typename Q = T,
1634 typename H = Hash,
1635 typename KE = KeyEqual,
1636 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE> && is_neither_convertible_v<K&&, iterator, const_iterator>,
1637 bool> = true>
1638 auto try_emplace(K&& key, Args&&... args) -> std::pair<iterator, bool> {
1639 return do_try_emplace(std::forward<K>(key), std::forward<Args>(args)...);
1640 }
1641
1642 template <
1643 typename K,
1644 typename... Args,
1645 typename Q = T,
1646 typename H = Hash,
1647 typename KE = KeyEqual,
1648 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE> && is_neither_convertible_v<K&&, iterator, const_iterator>,
1649 bool> = true>
1650 auto try_emplace(const_iterator /*hint*/, K&& key, Args&&... args) -> iterator {
1651 return do_try_emplace(std::forward<K>(key), std::forward<Args>(args)...).first;
1652 }
1653
1654 auto erase(iterator it) -> iterator {
1655 auto hash = mixed_hash(get_key(*it));
1656 auto bucket_idx = bucket_idx_from_hash(hash);
1657
1658 auto const value_idx_to_remove = static_cast<value_idx_type>(it - cbegin());
1659 while (at(m_buckets, bucket_idx).m_value_idx != value_idx_to_remove) {
1660 bucket_idx = next(bucket_idx);
1661 }
1662
1663 do_erase(bucket_idx, [](value_type&& /*unused*/) {
1664 });
1665 return begin() + static_cast<difference_type>(value_idx_to_remove);
1666 }
1667
1668 auto extract(iterator it) -> value_type {
1669 auto hash = mixed_hash(get_key(*it));
1670 auto bucket_idx = bucket_idx_from_hash(hash);
1671
1672 auto const value_idx_to_remove = static_cast<value_idx_type>(it - cbegin());
1673 while (at(m_buckets, bucket_idx).m_value_idx != value_idx_to_remove) {
1674 bucket_idx = next(bucket_idx);
1675 }
1676
1677 auto tmp = std::optional<value_type>{};
1678 do_erase(bucket_idx, [&tmp](value_type&& val) {
1679 tmp = std::move(val);
1680 });
1681 return std::move(tmp).value();
1682 }
1683
1684 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1685 auto erase(const_iterator it) -> iterator {
1686 return erase(begin() + (it - cbegin()));
1687 }
1688
1689 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1690 auto extract(const_iterator it) -> value_type {
1691 return extract(begin() + (it - cbegin()));
1692 }
1693
1694 auto erase(const_iterator first, const_iterator last) -> iterator {
1695 auto const idx_first = first - cbegin();
1696 auto const idx_last = last - cbegin();
1697 auto const first_to_last = std::distance(first, last);
1698 auto const last_to_end = std::distance(last, cend());
1699
1700 // remove elements from left to right which moves elements from the end back
1701 auto const mid = idx_first + (std::min)(first_to_last, last_to_end);
1702 auto idx = idx_first;
1703 while (idx != mid) {
1704 erase(begin() + idx);
1705 ++idx;
1706 }
1707
1708 // all elements from the right are moved, now remove the last element until all done
1709 idx = idx_last;
1710 while (idx != mid) {
1711 --idx;
1712 erase(begin() + idx);
1713 }
1714
1715 return begin() + idx_first;
1716 }
1717
1718 auto erase(Key const& key) -> size_t {
1719 return do_erase_key(key, [](value_type&& /*unused*/) {
1720 });
1721 }
1722
1723 auto extract(Key const& key) -> std::optional<value_type> {
1724 auto tmp = std::optional<value_type>{};
1725 do_erase_key(key, [&tmp](value_type&& val) {
1726 tmp = std::move(val);
1727 });
1728 return tmp;
1729 }
1730
1731 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1732 auto erase(K&& key) -> size_t {
1733 return do_erase_key(std::forward<K>(key), [](value_type&& /*unused*/) {
1734 });
1735 }
1736
1737 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1738 auto extract(K&& key) -> std::optional<value_type> {
1739 auto tmp = std::optional<value_type>{};
1740 do_erase_key(std::forward<K>(key), [&tmp](value_type&& val) {
1741 tmp = std::move(val);
1742 });
1743 return tmp;
1744 }
1745
1746 void swap(table& other) noexcept(noexcept(std::is_nothrow_swappable_v<value_container_type> &&
1747 std::is_nothrow_swappable_v<Hash> && std::is_nothrow_swappable_v<KeyEqual>)) {
1748 using std::swap;
1749 swap(other, *this);
1750 }
1751
1752 // lookup /////////////////////////////////////////////////////////////////
1753
1754 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1755 auto at(key_type const& key) -> Q& {
1756 return do_at(key);
1757 }
1758
1759 template <typename K,
1760 typename Q = T,
1761 typename H = Hash,
1762 typename KE = KeyEqual,
1763 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1764 auto at(K const& key) -> Q& {
1765 return do_at(key);
1766 }
1767
1768 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1769 auto at(key_type const& key) const -> Q const& {
1770 return do_at(key);
1771 }
1772
1773 template <typename K,
1774 typename Q = T,
1775 typename H = Hash,
1776 typename KE = KeyEqual,
1777 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1778 auto at(K const& key) const -> Q const& {
1779 return do_at(key);
1780 }
1781
1782 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1783 auto operator[](Key const& key) -> Q& {
1784 return try_emplace(key).first->second;
1785 }
1786
1787 template <typename Q = T, std::enable_if_t<is_map_v<Q>, bool> = true>
1788 auto operator[](Key&& key) -> Q& {
1789 return try_emplace(std::move(key)).first->second;
1790 }
1791
1792 template <typename K,
1793 typename Q = T,
1794 typename H = Hash,
1795 typename KE = KeyEqual,
1796 std::enable_if_t<is_map_v<Q> && is_transparent_v<H, KE>, bool> = true>
1797 auto operator[](K&& key) -> Q& {
1798 return try_emplace(std::forward<K>(key)).first->second;
1799 }
1800
1801 auto count(Key const& key) const -> size_t {
1802 return find(key) == end() ? 0 : 1;
1803 }
1804
1805 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1806 auto count(K const& key) const -> size_t {
1807 return find(key) == end() ? 0 : 1;
1808 }
1809
1810 auto find(Key const& key) -> iterator {
1811 return do_find(key);
1812 }
1813
1814 auto find(Key const& key) const -> const_iterator {
1815 return do_find(key);
1816 }
1817
1818 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1819 auto find(K const& key) -> iterator {
1820 return do_find(key);
1821 }
1822
1823 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1824 auto find(K const& key) const -> const_iterator {
1825 return do_find(key);
1826 }
1827
1828 auto contains(Key const& key) const -> bool {
1829 return find(key) != end();
1830 }
1831
1832 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1833 auto contains(K const& key) const -> bool {
1834 return find(key) != end();
1835 }
1836
1837 auto equal_range(Key const& key) -> std::pair<iterator, iterator> {
1838 auto it = do_find(key);
1839 return {it, it == end() ? end() : it + 1};
1840 }
1841
1842 auto equal_range(const Key& key) const -> std::pair<const_iterator, const_iterator> {
1843 auto it = do_find(key);
1844 return {it, it == end() ? end() : it + 1};
1845 }
1846
1847 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1848 auto equal_range(K const& key) -> std::pair<iterator, iterator> {
1849 auto it = do_find(key);
1850 return {it, it == end() ? end() : it + 1};
1851 }
1852
1853 template <class K, class H = Hash, class KE = KeyEqual, std::enable_if_t<is_transparent_v<H, KE>, bool> = true>
1854 auto equal_range(K const& key) const -> std::pair<const_iterator, const_iterator> {
1855 auto it = do_find(key);
1856 return {it, it == end() ? end() : it + 1};
1857 }
1858
1859 // bucket interface ///////////////////////////////////////////////////////
1860
1861 auto bucket_count() const noexcept -> size_t { // NOLINT(modernize-use-nodiscard)
1862 return m_buckets.size();
1863 }
1864
1865 static constexpr auto max_bucket_count() noexcept -> size_t { // NOLINT(modernize-use-nodiscard)
1866 return max_size();
1867 }
1868
1869 // hash policy ////////////////////////////////////////////////////////////
1870
1871 [[nodiscard]] auto load_factor() const -> float {
1872 return bucket_count() ? static_cast<float>(size()) / static_cast<float>(bucket_count()) : 0.0F;
1873 }
1874
1875 [[nodiscard]] auto max_load_factor() const -> float {
1876 return m_max_load_factor;
1877 }
1878
1879 void max_load_factor(float ml) {
1880 m_max_load_factor = ml;
1881 if (bucket_count() != max_bucket_count()) {
1882 m_max_bucket_capacity = static_cast<value_idx_type>(static_cast<float>(bucket_count()) * max_load_factor());
1883 }
1884 }
1885
1886 void rehash(size_t count) {
1887 count = (std::min)(count, max_size());
1888 auto shifts = calc_shifts_for_size((std::max)(count, size()));
1889 if (shifts != m_shifts) {
1890 m_shifts = shifts;
1891 deallocate_buckets();
1892 m_values.shrink_to_fit();
1893 allocate_buckets_from_shift();
1894 clear_and_fill_buckets_from_values();
1895 }
1896 }
1897
1898 void reserve(size_t capa) {
1899 capa = (std::min)(capa, max_size());
1900 if constexpr (has_reserve<value_container_type>) {
1901 // std::deque doesn't have reserve(). Make sure we only call when available
1902 m_values.reserve(capa);
1903 }
1904 auto shifts = calc_shifts_for_size((std::max)(capa, size()));
1905 if (0 == bucket_count() || shifts < m_shifts) {
1906 m_shifts = shifts;
1907 deallocate_buckets();
1908 allocate_buckets_from_shift();
1909 clear_and_fill_buckets_from_values();
1910 }
1911 }
1912
1913 // observers //////////////////////////////////////////////////////////////
1914
1915 auto hash_function() const -> hasher {
1916 return m_hash;
1917 }
1918
1919 auto key_eq() const -> key_equal {
1920 return m_equal;
1921 }
1922
1923 // nonstandard API: expose the underlying values container
1924 [[nodiscard]] auto values() const noexcept -> value_container_type const& {
1925 return m_values;
1926 }
1927
1928 // non-member functions ///////////////////////////////////////////////////
1929
1930 friend auto operator==(table const& a, table const& b) -> bool {
1931 if (&a == &b) {
1932 return true;
1933 }
1934 if (a.size() != b.size()) {
1935 return false;
1936 }
1937 for (auto const& b_entry : b) {
1938 auto it = a.find(get_key(b_entry));
1939 if constexpr (is_map_v<T>) {
1940 // map: check that key is here, then also check that value is the same
1941 if (a.end() == it || !(b_entry.second == it->second)) {
1942 return false;
1943 }
1944 } else {
1945 // set: only check that the key is here
1946 if (a.end() == it) {
1947 return false;
1948 }
1949 }
1950 }
1951 return true;
1952 }
1953
1954 friend auto operator!=(table const& a, table const& b) -> bool {
1955 return !(a == b);
1956 }
1957};
1958
1959} // namespace detail
1960
1961ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
1962 class T,
1963 class Hash = hash<Key>,
1964 class KeyEqual = std::equal_to<Key>,
1965 class AllocatorOrContainer = std::allocator<std::pair<Key, T>>,
1966 class Bucket = bucket_type::standard,
1967 class BucketContainer = detail::default_container_t>
1968using map = detail::table<Key, T, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, false>;
1969
1970ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
1971 class T,
1972 class Hash = hash<Key>,
1973 class KeyEqual = std::equal_to<Key>,
1974 class AllocatorOrContainer = std::allocator<std::pair<Key, T>>,
1975 class Bucket = bucket_type::standard,
1976 class BucketContainer = detail::default_container_t>
1977using segmented_map = detail::table<Key, T, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, true>;
1978
1979ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
1980 class Hash = hash<Key>,
1981 class KeyEqual = std::equal_to<Key>,
1982 class AllocatorOrContainer = std::allocator<Key>,
1983 class Bucket = bucket_type::standard,
1984 class BucketContainer = detail::default_container_t>
1985using set = detail::table<Key, void, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, false>;
1986
1987ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
1988 class Hash = hash<Key>,
1989 class KeyEqual = std::equal_to<Key>,
1990 class AllocatorOrContainer = std::allocator<Key>,
1991 class Bucket = bucket_type::standard,
1992 class BucketContainer = detail::default_container_t>
1993using segmented_set = detail::table<Key, void, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, true>;
1994
1995# if defined(ANKERL_UNORDERED_DENSE_PMR)
1996
1997namespace pmr {
1998
1999ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
2000 class T,
2001 class Hash = hash<Key>,
2002 class KeyEqual = std::equal_to<Key>,
2003 class Bucket = bucket_type::standard>
2004using map = detail::table<Key,
2005 T,
2006 Hash,
2007 KeyEqual,
2008 ANKERL_UNORDERED_DENSE_PMR::polymorphic_allocator<std::pair<Key, T>>,
2009 Bucket,
2010 detail::default_container_t,
2011 false>;
2012
2013ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
2014 class T,
2015 class Hash = hash<Key>,
2016 class KeyEqual = std::equal_to<Key>,
2017 class Bucket = bucket_type::standard>
2018using segmented_map = detail::table<Key,
2019 T,
2020 Hash,
2021 KeyEqual,
2022 ANKERL_UNORDERED_DENSE_PMR::polymorphic_allocator<std::pair<Key, T>>,
2023 Bucket,
2024 detail::default_container_t,
2025 true>;
2026
2027ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
2028 class Hash = hash<Key>,
2029 class KeyEqual = std::equal_to<Key>,
2030 class Bucket = bucket_type::standard>
2031using set = detail::table<Key,
2032 void,
2033 Hash,
2034 KeyEqual,
2035 ANKERL_UNORDERED_DENSE_PMR::polymorphic_allocator<Key>,
2036 Bucket,
2037 detail::default_container_t,
2038 false>;
2039
2040ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
2041 class Hash = hash<Key>,
2042 class KeyEqual = std::equal_to<Key>,
2043 class Bucket = bucket_type::standard>
2044using segmented_set = detail::table<Key,
2045 void,
2046 Hash,
2047 KeyEqual,
2048 ANKERL_UNORDERED_DENSE_PMR::polymorphic_allocator<Key>,
2049 Bucket,
2050 detail::default_container_t,
2051 true>;
2052
2053} // namespace pmr
2054
2055# endif
2056
2057// deduction guides ///////////////////////////////////////////////////////////
2058
2059// deduction guides for alias templates are only possible since C++20
2060// see https://en.cppreference.com/w/cpp/language/class_template_argument_deduction
2061
2062} // namespace ANKERL_UNORDERED_DENSE_NAMESPACE
2063} // namespace ankerl::unordered_dense
2064
2065// std extensions /////////////////////////////////////////////////////////////
2066
2067namespace std { // NOLINT(cert-dcl58-cpp)
2068
2069ANKERL_UNORDERED_DENSE_EXPORT template <class Key,
2070 class T,
2071 class Hash,
2072 class KeyEqual,
2073 class AllocatorOrContainer,
2074 class Bucket,
2075 class Pred,
2076 class BucketContainer,
2077 bool IsSegmented>
2078// NOLINTNEXTLINE(cert-dcl58-cpp)
2079auto erase_if(
2080 ankerl::unordered_dense::detail::table<Key, T, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, IsSegmented>&
2081 map,
2082 Pred pred) -> size_t {
2083 using map_t = ankerl::unordered_dense::detail::
2084 table<Key, T, Hash, KeyEqual, AllocatorOrContainer, Bucket, BucketContainer, IsSegmented>;
2085
2086 // going back to front because erase() invalidates the end iterator
2087 auto const old_size = map.size();
2088 auto idx = old_size;
2089 while (idx) {
2090 --idx;
2091 auto it = map.begin() + static_cast<typename map_t::difference_type>(idx);
2092 if (pred(*it)) {
2093 map.erase(it);
2094 }
2095 }
2096
2097 return old_size - map.size();
2098}
2099
2100} // namespace std
2101
2102#endif
2103#endif
bool operator!=(const Version &lhs, const Version &rhs)
Definition Version.hpp:74
bool operator==(const Version &lhs, const Version &rhs)
Definition Version.hpp:67
constexpr Rect operator-(const Rect &lhs, const Rect &rhs)
Rectangle subtraction operator.
Definition Rect.hpp:371
constexpr t_Vector2< T > operator*(const t_Vector2< T > &lhs, T rhs)
Scalar multiplication.
Definition Vector2.hpp:646
constexpr Rect operator+(const Rect &lhs, const Rect &rhs)
Rectangle addition operator.
Definition Rect.hpp:398
Vector3 INFINITY_API_PUBLIC mix(const Vector3 &a, const Vector3 &b, float t)
Linear interpolation between two 3D vectors (alias for lerp).
constexpr auto size(const C &c) -> decltype(c.size())
Definition Span.hpp:185
void void_t
Definition Span.hpp:225
Definition Span.hpp:599