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