GREM 3.12.0
Game/Rendering Engine Modules for C++
Loading...
Searching...
No Matches
HashMap.hpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Ivar Härnqvist
2// SPDX-License-Identifier: MIT
3
4#ifndef GREM_CORE_DATA_HASH_MAP_HPP
5#define GREM_CORE_DATA_HASH_MAP_HPP
6
8
11
12#include <algorithm> // std::min, std::max, std::equal, std::lexicographical_compare
13#include <bit> // std::countr_zero, std::countl_zero
14#include <cstddef> // std::size_t, std::ptrdiff_t
15#include <cstdint> // std::uint32_t, std::uint64_t
16#include <cstring> // std::memset, std::memcpy
17#include <functional> // std::hash, std::equal_to
18#include <initializer_list> // std::initializer_list
19#include <iterator> // std::input_iterator, std::sentinel_for, std::iterator_traits, std::..._iterator_tag, std::next, std::begin, std::end
20#include <limits> // std::numeric_limits
21#include <memory> // std::allocator, std::allocator_traits, std::to_address, std::addressof
22#include <memory_resource> // std::pmr::polymorphic_allocator
23#include <stdexcept> // std::out_of_range, std::length_error
24#include <type_traits> // std::is_..._v, std::remove_..._t, std::conditional_t
25#include <utility> // std::move, std::forward, std::exchange, std::swap
26
27namespace grem {
28
29template <typename Key, typename T, typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key>, typename Allocator = std::allocator<Pair<const Key, T>>>
30class HashMap {
31private:
32 static constexpr bool IS_TRANSPARENT = requires {
33 typename Hash::is_transparent;
34 typename KeyEqual::is_transparent;
35 };
36
37public:
38 using key_type = Key;
39 using mapped_type = T;
40 using size_type = std::size_t;
41 using hasher = Hash;
42 using key_equal = KeyEqual;
43 using allocator_type = Allocator;
44
45private:
46 template <bool Const>
47 class Iterator {
48 private:
49 using Map = std::conditional_t<Const, const HashMap, HashMap>;
50
51 public:
54 using difference_type = std::ptrdiff_t;
55 using iterator_category = std::bidirectional_iterator_tag;
56
57 struct pointer {
58 reference ref;
59
60 [[nodiscard]] constexpr reference* operator->() noexcept {
61 return &ref;
62 }
63 };
64
65 Iterator() noexcept = default;
66
67 constexpr Iterator(Map* map, size_type index) noexcept
68 : map(map)
69 , index(index) {}
70
71 constexpr operator Iterator<true>() const noexcept requires(!Const) {
72 return Iterator<true>{map, index};
73 }
74
75 [[nodiscard]] constexpr reference operator*() const {
76 GREM_ASSERT(map);
77 GREM_ASSERT(index < map->elementCapacity);
78 return reference{map->keys[index], map->values[index]};
79 }
80
81 [[nodiscard]] constexpr pointer operator->() const {
82 return pointer{**this};
83 }
84
85 constexpr Iterator& operator++() {
86 GREM_ASSERT(map);
87 GREM_ASSERT(index < map->elementCapacity);
88 GREM_ASSERT(map->elementCount > 0);
89 index = map->findActiveIndexUnbounded(index + 1);
90 return *this;
91 }
92
93 constexpr Iterator operator++(int) {
94 Iterator old = *this;
95 ++*this;
96 return old;
97 }
98
99 constexpr Iterator& operator--() {
100 GREM_ASSERT(map);
101 GREM_ASSERT(index > 0);
102 GREM_ASSERT(map->elementCount > 0);
103 index = map->findActiveIndexReverseUnbounded(index - 1);
104 return *this;
105 }
106
107 constexpr Iterator operator--(int) {
108 Iterator old = *this;
109 --*this;
110 return old;
111 }
112
113 [[nodiscard]] constexpr bool operator==(const Iterator& other) const {
114 GREM_ASSERT(map == other.map);
115 return index == other.index;
116 }
117
118 [[nodiscard]] constexpr size_type getIndex() const noexcept {
119 return index;
120 }
121
122 private:
123 friend HashMap;
124
125 Map* map = nullptr;
126 size_type index = 0;
127 };
128
129public:
130 using iterator = Iterator<false>;
131 using const_iterator = Iterator<true>;
132 using value_type = typename iterator::value_type;
133 using reference = typename iterator::reference;
134 using const_reference = typename const_iterator::reference;
135 using pointer = typename iterator::pointer;
136 using const_pointer = typename const_iterator::pointer;
137 using difference_type = typename iterator::difference_type;
138
139 constexpr HashMap() noexcept = default;
140
141 constexpr explicit HashMap(size_type bucket_count, const Hash& hash = Hash(), const KeyEqual& equal = KeyEqual(), const Allocator& allocator = Allocator())
142 : HashMap(hash, equal, allocator) {
143 reserve(bucket_count);
144 }
145
146 constexpr HashMap(size_type bucket_count, const Allocator& allocator)
147 : HashMap(bucket_count, Hash(), KeyEqual(), allocator) {}
148
149 constexpr HashMap(size_type bucket_count, const Hash& hash, const Allocator& allocator)
150 : HashMap(bucket_count, hash, KeyEqual(), allocator) {}
151
152 constexpr explicit HashMap(const Allocator& allocator)
153 : HashMap(Hash(), KeyEqual(), allocator) {}
154
155 template <std::input_iterator InputIterator, std::sentinel_for<InputIterator> Sentinel>
156 constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count = 0, const Hash& hash = Hash(), const KeyEqual& equal = KeyEqual(),
157 const Allocator& allocator = Allocator())
158 : HashMap(bucket_count, hash, equal, allocator) {
159 insert(first, last);
160 }
161
162 template <std::input_iterator InputIterator, std::sentinel_for<InputIterator> Sentinel>
163 constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count, const Allocator& allocator)
164 : HashMap(first, last, bucket_count, Hash(), KeyEqual(), allocator) {}
165
166 template <std::input_iterator InputIterator, std::sentinel_for<InputIterator> Sentinel>
167 constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count, const Hash& hash, const Allocator& allocator)
168 : HashMap(first, last, bucket_count, hash, KeyEqual(), allocator) {}
169
170 constexpr HashMap(std::initializer_list<value_type> ilist, size_type bucket_count = 0, const Hash& hash = Hash(), const KeyEqual& equal = KeyEqual(),
171 const Allocator& allocator = Allocator())
172 : HashMap(ilist.begin(), ilist.end(), bucket_count, hash, equal, allocator) {}
173
174 constexpr HashMap(std::initializer_list<value_type> ilist, size_type bucket_count, const Allocator& allocator = Allocator())
175 : HashMap(ilist, bucket_count, Hash(), KeyEqual(), allocator) {}
176
177 constexpr HashMap(std::initializer_list<value_type> ilist, size_type bucket_count, const Hash& hash = Hash(), const Allocator& allocator = Allocator())
178 : HashMap(ilist, bucket_count, hash, KeyEqual(), allocator) {}
179
180 constexpr HashMap(const HashMap& other)
181 : HashMap(other, std::allocator_traits<Allocator>::select_on_container_copy_construction(other.get_allocator())) {}
182
183 constexpr HashMap(const HashMap& other, const Allocator& allocator)
184 : HashMap(allocator) {
185 *this = other;
186 }
187
188 constexpr HashMap(HashMap&& other) noexcept
189 : activeBits(std::exchange(other.activeBits, nullptr))
190 , bucketExtents(std::exchange(other.bucketExtents, nullptr))
191 , keys(std::exchange(other.keys, nullptr))
192 , values(std::exchange(other.values, nullptr))
193 , elementCount(std::exchange(other.elementCount, size_type{0}))
194 , elementCapacity(std::exchange(other.elementCapacity, size_type{0}))
195 , hash(std::move(other.hash))
196 , equal(std::move(other.equal))
197 , allocator(other.get_allocator()) {}
198
199 constexpr HashMap(HashMap&& other, const Allocator& allocator) noexcept // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
200 : HashMap(allocator) {
201 if constexpr (!std::allocator_traits<Allocator>::is_always_equal::value) {
202 if (allocator != other.get_allocator()) {
203 reserve(other.size());
204 for (reference element : other) {
205 if constexpr (std::is_nothrow_move_constructible_v<Key> && std::is_nothrow_move_constructible_v<T>) {
206 emplace(std::move(const_cast<Key&>(element.first)), std::move(element.second));
207 } else {
208 emplace(element.first, element.second);
209 }
210 }
211 other.clear();
212 return;
213 }
214 }
215 activeBits = std::exchange(other.activeBits, nullptr);
216 bucketExtents = std::exchange(other.bucketExtents, nullptr);
217 keys = std::exchange(other.keys, nullptr);
218 values = std::exchange(other.values, nullptr);
219 elementCount = std::exchange(other.elementCount, size_type{0});
220 elementCapacity = std::exchange(other.elementCapacity, size_type{0});
221 hash = std::move(other.hash);
222 equal = std::move(other.equal);
223 }
224
225 constexpr ~HashMap() {
226 reset();
227 }
228
229 constexpr HashMap& operator=(const HashMap& other) {
230 if (this == &other) {
231 return *this;
232 }
233 if constexpr (std::allocator_traits<Allocator>::propagate_on_container_copy_assignment::value) {
234 if constexpr (!std::allocator_traits<Allocator>::is_always_equal::value) {
235 if (allocator != other.get_allocator()) {
236 reset();
237 }
238 }
239 allocator = other.get_allocator();
240 }
241 clear();
242 if (elementCapacity == other.elementCapacity) {
243 if (other.elementCount > 0) {
244 GREM_ASSERT(elementCapacity > 0);
245 GREM_ASSERT(elementCapacity % 64 == 0);
246 KeyAllocator keyAllocator = allocator;
247 ValueAllocator valueAllocator = allocator;
248 const size_type begin = other.findActiveIndexUnbounded(0);
249 for (size_type index = begin; index < elementCapacity; index = other.findActiveIndexUnbounded(index + 1)) {
250 try {
251 std::allocator_traits<KeyAllocator>::construct(keyAllocator, std::to_address(keys) + index, other.keys[index]);
252 try {
253 std::allocator_traits<ValueAllocator>::construct(valueAllocator, std::to_address(values) + index, other.values[index]);
254 } catch (...) {
255 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
256 throw;
257 }
258 } catch (...) {
259 while (index != begin) {
260 index = other.findActiveIndexReverseUnbounded(index - 1);
261 std::allocator_traits<ValueAllocator>::destroy(valueAllocator, std::to_address(values) + index);
262 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
263 }
264 throw;
265 }
266 }
267 std::memcpy(std::to_address(activeBits), std::to_address(other.activeBits), (elementCapacity / 64) * sizeof(std::uint64_t));
268 std::memcpy(std::to_address(bucketExtents), std::to_address(other.bucketExtents), elementCapacity * sizeof(std::uint32_t));
269 elementCount = other.elementCount;
270 }
271 } else {
272 for (const_reference element : other) {
273 insert(element);
274 }
275 }
276 return *this;
277 }
278
279 constexpr HashMap& operator=(HashMap&& other) noexcept {
280 if (this == &other) {
281 return *this;
282 }
283 if constexpr (!std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value) {
284 if constexpr (!std::allocator_traits<Allocator>::is_always_equal::value) {
285 if (allocator != other.get_allocator()) {
286 clear();
287 reserve(other.size());
288 for (reference element : other) {
289 if constexpr (std::is_nothrow_move_constructible_v<Key> && std::is_nothrow_move_constructible_v<T>) {
290 emplace(std::move(const_cast<Key&>(element.first)), std::move(element.second));
291 } else {
292 emplace(element.first, element.second);
293 }
294 }
295 other.clear();
296 return *this;
297 }
298 }
299 }
300 reset();
301 activeBits = std::exchange(other.activeBits, nullptr);
302 bucketExtents = std::exchange(other.bucketExtents, nullptr);
303 keys = std::exchange(other.keys, nullptr);
304 values = std::exchange(other.values, nullptr);
305 elementCount = std::exchange(other.elementCount, size_type{0});
306 elementCapacity = std::exchange(other.elementCapacity, size_type{0});
307 hash = std::move(other.hash);
308 equal = std::move(other.equal);
309 if constexpr (std::allocator_traits<Allocator>::propagate_on_container_move_assignment::value) {
310 allocator = other.get_allocator();
311 }
312 return *this;
313 }
314
315 constexpr HashMap& operator=(std::initializer_list<value_type> ilist) {
316 clear();
317 insert(ilist);
318 return *this;
319 }
320
321 constexpr void swap(HashMap& other) noexcept(std::allocator_traits<Allocator>::is_always_equal::value) { // NOLINT(cppcoreguidelines-noexcept-swap, performance-noexcept-swap)
322 if (this == &other) {
323 return;
324 }
325 using std::swap;
326 swap(activeBits, other.activeBits);
327 swap(bucketExtents, other.bucketExtents);
328 swap(keys, other.keys);
329 swap(values, other.values);
330 swap(elementCount, other.elementCount);
331 swap(elementCapacity, other.elementCapacity);
332 swap(hash, other.hash);
333 swap(equal, other.equal);
334 if constexpr (std::allocator_traits<Allocator>::propagate_on_container_swap::value) {
335 swap(allocator, other.allocator);
336 } else if constexpr (!std::allocator_traits<Allocator>::is_always_equal::value) {
337 GREM_ASSERT(allocator == other.allocator);
338 }
339 }
340
341 friend constexpr void swap(HashMap& a, HashMap& b) noexcept(noexcept(a.swap(b))) { // NOLINT(cppcoreguidelines-noexcept-swap, performance-noexcept-swap)
342 a.swap(b);
343 }
344
345 constexpr void clear() noexcept {
346 if (elementCount > 0) {
347 GREM_ASSERT(elementCapacity > 0);
348 GREM_ASSERT(elementCapacity % 64 == 0);
349 KeyAllocator keyAllocator = allocator;
350 ValueAllocator valueAllocator = allocator;
351 for (size_type index = findActiveIndexUnbounded(0); index < elementCapacity; index = findActiveIndexUnbounded(index + 1)) {
352 std::allocator_traits<ValueAllocator>::destroy(valueAllocator, std::to_address(values) + index);
353 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
354 }
355 std::memset(std::to_address(activeBits), 0, (elementCapacity / 64) * sizeof(std::uint64_t));
356 std::memset(std::to_address(bucketExtents), 0, elementCapacity * sizeof(std::uint32_t));
357 elementCount = 0;
358 }
359 }
360
361 constexpr void reserve(size_type capacity) {
362 size_type newCapacity = std::max(elementCapacity, size_type{64});
363 while (static_cast<float>(capacity) > static_cast<float>(newCapacity) * MAX_SIZE_PER_CAPACITY) {
364 if (newCapacity >= std::numeric_limits<size_type>::max() / 2) {
365 throw std::length_error{"Maximum capacity exceeded."};
366 }
367 newCapacity *= 2;
368 }
369 if (newCapacity <= elementCapacity) {
370 return;
371 }
372
373 GREM_ASSERT(newCapacity % 64 == 0);
374 GREM_ASSERT((newCapacity & (newCapacity - 1)) == 0);
375
376 HashMap newMap{hash, equal, allocator};
377 UInt64Allocator uInt64Allocator = allocator;
378 UInt32Allocator uInt32Allocator = allocator;
379 KeyAllocator keyAllocator = allocator;
380 ValueAllocator valueAllocator = allocator;
381 newMap.activeBits = std::allocator_traits<UInt64Allocator>::allocate(uInt64Allocator, newCapacity / 64 + 1);
382 try {
383 newMap.bucketExtents = std::allocator_traits<UInt32Allocator>::allocate(uInt32Allocator, newCapacity);
384 try {
385 newMap.keys = std::allocator_traits<KeyAllocator>::allocate(keyAllocator, newCapacity);
386 try {
387 newMap.values = std::allocator_traits<ValueAllocator>::allocate(valueAllocator, newCapacity);
388 } catch (...) {
389 std::allocator_traits<KeyAllocator>::deallocate(keyAllocator, newMap.keys, newCapacity);
390 throw;
391 }
392 } catch (...) {
393 std::allocator_traits<UInt32Allocator>::deallocate(uInt32Allocator, newMap.bucketExtents, newCapacity);
394 throw;
395 }
396 } catch (...) {
397 std::allocator_traits<UInt64Allocator>::deallocate(uInt64Allocator, newMap.activeBits, newCapacity / 64 + 1);
398 throw;
399 }
400 std::memset(std::to_address(newMap.activeBits), 0, (newCapacity / 64) * sizeof(std::uint64_t));
401 newMap.activeBits[newCapacity / 64] = 1;
402 std::memset(std::to_address(newMap.bucketExtents), 0, newCapacity * sizeof(std::uint32_t));
403 newMap.elementCapacity = newCapacity;
404
405 for (reference element : *this) {
406 if constexpr (std::is_nothrow_move_constructible_v<Key> && std::is_nothrow_move_constructible_v<T>) {
407 newMap.emplace(std::move(const_cast<Key&>(element.first)), std::move(element.second));
408 } else {
409 newMap.emplace(element.first, element.second);
410 }
411 }
412 GREM_ASSERT(allocator == newMap.get_allocator());
413 *this = std::move(newMap);
414 }
415
416 constexpr Pair<iterator, bool> insert(const value_type& value) {
417 return try_emplace(value.first, value.second);
418 }
419
420 constexpr Pair<iterator, bool> insert(value_type&& value) { // NOLINT(cppcoreguidelines-rvalue-reference-param-not-moved)
421 return try_emplace(std::move(value.first), std::move(value.second));
422 }
423
424 template <typename P>
425 constexpr Pair<iterator, bool> insert(P&& value) requires(std::is_constructible_v<value_type, P &&>) {
426 return emplace(std::forward<P>(value));
427 }
428
429 template <std::input_iterator InputIterator, std::sentinel_for<InputIterator> Sentinel>
430 constexpr void insert(InputIterator first, Sentinel last) {
431 if constexpr (std::is_convertible_v<typename std::iterator_traits<InputIterator>::iterator_category, std::random_access_iterator_tag>) {
432 reserve(size() + static_cast<size_type>(last - first));
433 }
434 while (first != last) {
435 insert(*first++);
436 }
437 }
438
439 constexpr void insert(std::initializer_list<value_type> ilist) {
440 insert(ilist.begin(), ilist.end());
441 }
442
443 template <typename R>
444 constexpr void insert_range(R&& r) { // NOLINT(cppcoreguidelines-missing-std-forward)
445 insert(std::begin(r), std::end(r));
446 }
447
448 template <typename... Args>
449 constexpr Pair<iterator, bool> emplace(Args&&... args) {
450 return insert(value_type(std::forward<Args>(args)...));
451 }
452
453 template <typename... Args>
454 constexpr Pair<iterator, bool> try_emplace(const Key& k, Args&&... args) {
455 return try_emplace(Key(k), std::forward<Args>(args)...);
456 }
457
458 template <typename... Args>
459 constexpr Pair<iterator, bool> try_emplace(Key&& k, Args&&... args) {
460 return insertAndConstruct(std::move(k), std::forward<Args>(args)...);
461 }
462
463 template <typename K, typename... Args>
464 constexpr Pair<iterator, bool> try_emplace(K&& k, Args&&... args)
465 requires(!std::is_convertible_v<K &&, const_iterator> && !std::is_convertible_v<K &&, iterator> && IS_TRANSPARENT) {
466 return insertAndConstruct(std::forward<K>(k), std::forward<Args>(args)...);
467 }
468
469 template <typename M>
470 constexpr Pair<iterator, bool> insert_or_assign(const Key& k, M&& obj) {
471 const auto result = try_emplace(k, std::forward<M>(obj));
472 if (!result.second) {
473 result.first->second = std::forward<M>(obj);
474 }
475 return result;
476 }
477
478 template <typename M>
479 constexpr Pair<iterator, bool> insert_or_assign(Key&& k, M&& obj) {
480 const auto result = try_emplace(std::move(k), std::forward<M>(obj));
481 if (!result.second) {
482 result.first->second = std::forward<M>(obj);
483 }
484 return result;
485 }
486
487 template <typename K, typename M>
488 constexpr Pair<iterator, bool> insert_or_assign(K&& k, M&& obj) requires(IS_TRANSPARENT) {
489 const auto result = try_emplace(std::forward<K>(k), std::forward<M>(obj));
490 if (!result.second) {
491 result.first->second = std::forward<M>(obj);
492 }
493 return result;
494 }
495
497 return iterator{this, eraseAtIndex(pos.index)};
498 }
499
501 while (first != last) {
502 first = erase(first);
503 }
504 return iterator{this, first.index};
505 }
506
507 constexpr size_type erase(const Key& key) {
508 return eraseKey(key);
509 }
510
511 template <typename K>
512 constexpr size_type erase(K&& x) requires(IS_TRANSPARENT && !std::is_convertible_v<K, iterator> && !std::is_convertible_v<K, const_iterator>) {
513 return eraseKey(std::forward<K>(x));
514 }
515
516 template <typename Predicate>
517 friend constexpr size_type erase_if(HashMap& c, Predicate predicate) {
518 const size_type oldSize = c.size();
519 iterator it = c.begin();
520 while (it != c.end()) {
521 if (predicate(*it)) {
522 it = c.erase(it);
523 } else {
524 ++it;
525 }
526 }
527 return oldSize - c.size();
528 }
529
530 [[nodiscard]] constexpr hasher hash_function() const {
531 return hash;
532 }
533
534 [[nodiscard]] constexpr key_equal key_eq() const {
535 return equal;
536 }
537
538 [[nodiscard]] constexpr allocator_type get_allocator() const noexcept {
539 return allocator;
540 }
541
542 [[nodiscard]] constexpr bool empty() const noexcept {
543 return elementCount == 0;
544 }
545
546 [[nodiscard]] constexpr size_type size() const noexcept {
547 return elementCount;
548 }
549
550 [[nodiscard]] constexpr size_type max_size() const noexcept {
551 static_assert(MAX_SIZE_PER_CAPACITY <= 1.0f);
552 return static_cast<size_type>(
553 static_cast<float>(std::min({
554 static_cast<size_type>(std::numeric_limits<difference_type>::max()),
555 static_cast<size_type>(std::numeric_limits<size_type>::max() / sizeof(std::uint32_t)),
556 static_cast<size_type>(std::numeric_limits<size_type>::max() / sizeof(Key)),
557 static_cast<size_type>(std::numeric_limits<size_type>::max() / sizeof(T)),
558 static_cast<size_type>(std::allocator_traits<UInt32Allocator>::max_size(allocator)),
559 static_cast<size_type>(std::allocator_traits<KeyAllocator>::max_size(allocator)),
560 static_cast<size_type>(std::allocator_traits<ValueAllocator>::max_size(allocator)),
561 })) *
562 MAX_SIZE_PER_CAPACITY);
563 }
564
565 [[nodiscard]] constexpr T& at(const Key& key) {
566 if (const iterator it = find(key); it != end()) {
567 return it->second;
568 }
569 throw std::out_of_range{"!contains(key)"};
570 }
571
572 [[nodiscard]] constexpr const T& at(const Key& key) const {
573 if (const const_iterator it = find(key); it != end()) {
574 return it->second;
575 }
576 throw std::out_of_range{"!contains(key)"};
577 }
578
579 template <typename K>
580 [[nodiscard]] constexpr T& at(const K& key) requires(IS_TRANSPARENT) {
581 if (const iterator it = find(key); it != end()) {
582 return it->second;
583 }
584 throw std::out_of_range{"!contains(key)"};
585 }
586
587 template <typename K>
588 [[nodiscard]] constexpr const T& at(const K& key) const requires(IS_TRANSPARENT) {
589 if (const const_iterator it = find(key); it != end()) {
590 return it->second;
591 }
592 throw std::out_of_range{"!contains(key)"};
593 }
594
595 [[nodiscard]] constexpr T& operator[](const Key& key) {
596 return try_emplace(key).first->second;
597 }
598
599 [[nodiscard]] constexpr T& operator[](Key&& key) {
600 return try_emplace(std::move(key)).first->second;
601 }
602
603 template <typename K>
604 [[nodiscard]] constexpr T& operator[](K&& x) requires(IS_TRANSPARENT) {
605 return try_emplace(std::forward<K>(x)).first->second;
606 }
607
608 [[nodiscard]] constexpr bool contains(const Key& key) const {
609 return find(key) != end();
610 }
611
612 template <typename K>
613 [[nodiscard]] constexpr bool contains(const K& x) const requires(IS_TRANSPARENT) {
614 return find(x) != end();
615 }
616
617 [[nodiscard]] constexpr size_type count(const Key& key) const {
618 return (contains(key)) ? 1 : 0;
619 }
620
621 template <typename K>
622 [[nodiscard]] constexpr size_type count(const K& x) const requires(IS_TRANSPARENT) {
623 return (contains(x)) ? 1 : 0;
624 }
625
626 [[nodiscard]] constexpr iterator find(const Key& key) {
627 return iterator{this, findIndex(key)};
628 }
629
630 [[nodiscard]] constexpr const_iterator find(const Key& key) const {
631 return const_iterator{this, findIndex(key)};
632 }
633
634 template <typename K>
635 [[nodiscard]] constexpr iterator find(const K& x) requires(IS_TRANSPARENT) {
636 return iterator{this, findIndex(x)};
637 }
638
639 template <typename K>
640 [[nodiscard]] constexpr const_iterator find(const K& x) const requires(IS_TRANSPARENT) {
641 return const_iterator{this, findIndex(x)};
642 }
643
644 [[nodiscard]] constexpr iterator getIteratorAtIndex(size_type index) {
645 GREM_ASSERT(index <= elementCapacity);
646 return iterator{this, index};
647 }
648
649 [[nodiscard]] constexpr const_iterator getIteratorAtIndex(size_type index) const {
650 GREM_ASSERT(index <= elementCapacity);
651 return const_iterator{this, index};
652 }
653
654 [[nodiscard]] constexpr reference getAtIndex(size_type index) {
655 GREM_ASSERT(index <= elementCapacity);
656 GREM_ASSERT(isActive(index));
657 return *iterator{this, index};
658 }
659
660 [[nodiscard]] constexpr const_reference getAtIndex(size_type index) const {
661 GREM_ASSERT(index <= elementCapacity);
662 GREM_ASSERT(isActive(index));
663 return *const_iterator{this, index};
664 }
665
666 [[nodiscard]] constexpr Pair<iterator, iterator> equal_range(const Key& key) {
667 const iterator it = find(key);
668 if (it != end()) {
669 return {it, std::next(it)};
670 }
671 return {it, it};
672 }
673
674 [[nodiscard]] constexpr Pair<const_iterator, const_iterator> equal_range(const Key& key) const {
675 const const_iterator it = find(key);
676 if (it != end()) {
677 return {it, std::next(it)};
678 }
679 return {it, it};
680 }
681
682 template <typename K>
683 [[nodiscard]] constexpr Pair<iterator, iterator> equal_range(const K& x) requires(IS_TRANSPARENT) {
684 const iterator it = find(x);
685 if (it != end()) {
686 return {it, std::next(it)};
687 }
688 return {it, it};
689 }
690
691 template <typename K>
692 [[nodiscard]] constexpr Pair<const_iterator, const_iterator> equal_range(const K& x) const requires(IS_TRANSPARENT) {
693 const const_iterator it = find(x);
694 if (it != end()) {
695 return {it, std::next(it)};
696 }
697 return {it, it};
698 }
699
700 [[nodiscard]] constexpr iterator begin() noexcept {
701 return iterator{this, (elementCount > 0) ? findActiveIndexUnbounded(0) : elementCapacity};
702 }
703
704 [[nodiscard]] constexpr const_iterator begin() const noexcept {
705 return const_iterator{this, (elementCount > 0) ? findActiveIndexUnbounded(0) : elementCapacity};
706 }
707
708 [[nodiscard]] constexpr const_iterator cbegin() const noexcept {
709 return begin();
710 }
711
712 [[nodiscard]] constexpr iterator end() noexcept {
713 return iterator{this, elementCapacity};
714 }
715
716 [[nodiscard]] constexpr const_iterator end() const noexcept {
717 return const_iterator{this, elementCapacity};
718 }
719
720 [[nodiscard]] constexpr const_iterator cend() const noexcept {
721 return end();
722 }
723
724 [[nodiscard]] constexpr bool operator==(const HashMap& other) const {
725 return std::equal(begin(), end(), other.begin(), other.end());
726 }
727
728 [[nodiscard]] constexpr bool operator<(const HashMap& other) const {
729 return std::lexicographical_compare(begin(), end(), other.begin(), other.end());
730 }
731
732 [[nodiscard]] constexpr bool operator<=(const HashMap& other) const {
733 return !(other < *this);
734 }
735
736 [[nodiscard]] constexpr bool operator>(const HashMap& other) const {
737 return other < *this;
738 }
739
740 [[nodiscard]] constexpr bool operator>=(const HashMap& other) const {
741 return !(*this < other);
742 }
743
744private:
745 static constexpr float MAX_SIZE_PER_CAPACITY = 0.7f;
746
747 using UInt64Allocator = typename std::allocator_traits<Allocator>::template rebind_alloc<std::uint64_t>;
748 using UInt32Allocator = typename std::allocator_traits<Allocator>::template rebind_alloc<std::uint32_t>;
749 using KeyAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<Key>;
750 using ValueAllocator = typename std::allocator_traits<Allocator>::template rebind_alloc<T>;
751
752 constexpr HashMap(const Hash& hash, const KeyEqual& equal, const Allocator& allocator)
753 : hash(hash)
754 , equal(equal)
755 , allocator(allocator) {}
756
757 [[nodiscard]] constexpr size_type getBucketIndexOfHash(std::size_t hashCode) const noexcept {
758 GREM_ASSERT((elementCapacity & (elementCapacity - 1)) == 0);
759 return static_cast<size_type>(hashCode) & static_cast<size_type>(elementCapacity - 1);
760 }
761
762 [[nodiscard]] constexpr size_type getWrappedIndex(size_type index) const noexcept {
763 GREM_ASSERT(elementCapacity > 0);
764 GREM_ASSERT((elementCapacity & (elementCapacity - 1)) == 0);
765 return index & static_cast<size_type>(elementCapacity - 1);
766 }
767
768 [[nodiscard]] constexpr bool isActive(size_type index) const {
769 return (activeBits[index / 64] & (std::uint64_t{1} << (index % 64))) != 0;
770 }
771
772 constexpr void setActive(size_type index) {
773 activeBits[index / 64] |= std::uint64_t{1} << (index % 64);
774 }
775
776 constexpr void clearActive(size_type index) {
777 activeBits[index / 64] &= ~(std::uint64_t{1} << (index % 64));
778 }
779
780 [[nodiscard]] constexpr size_type findActiveIndexUnbounded(size_type index) const {
781 while (true) {
782 const std::uint64_t bitsIndex = index / 64;
783 const std::uint64_t bitOffset = index % 64;
784 const std::uint64_t bits = activeBits[bitsIndex] >> bitOffset;
785 if (bits != 0) {
786 index += static_cast<size_type>(std::countr_zero(bits));
787 break;
788 }
789 index += 64 - bitOffset;
790 }
791 return index;
792 }
793
794 [[nodiscard]] constexpr size_type findActiveIndexReverseUnbounded(size_type index) const {
795 while (true) {
796 const std::uint64_t bitsIndex = index / 64;
797 const std::uint64_t bitOffset = index % 64;
798 const std::uint64_t bits = activeBits[bitsIndex] << (63 - bitOffset);
799 if (bits != 0) {
800 index -= static_cast<size_type>(std::countl_zero(bits));
801 break;
802 }
803 index -= bitOffset + 1;
804 }
805 return index;
806 }
807
808 constexpr void reset() noexcept {
809 clear();
810 if (elementCapacity > 0) {
811 GREM_ASSERT(elementCapacity % 64 == 0);
812 UInt64Allocator uInt64Allocator = allocator;
813 UInt32Allocator uInt32Allocator = allocator;
814 KeyAllocator keyAllocator = allocator;
815 ValueAllocator valueAllocator = allocator;
816 std::allocator_traits<UInt64Allocator>::deallocate(uInt64Allocator, activeBits, elementCapacity / 64 + 1);
817 std::allocator_traits<UInt32Allocator>::deallocate(uInt32Allocator, bucketExtents, elementCapacity);
818 std::allocator_traits<KeyAllocator>::deallocate(keyAllocator, keys, elementCapacity);
819 std::allocator_traits<ValueAllocator>::deallocate(valueAllocator, values, elementCapacity);
820 activeBits = nullptr;
821 bucketExtents = nullptr;
822 keys = nullptr;
823 values = nullptr;
824 elementCapacity = 0;
825 }
826 }
827
828 template <typename K, typename... Args>
829 [[nodiscard]] constexpr Pair<iterator, bool> insertAndConstruct(K&& k, Args&&... args) {
830 if (size() >= max_size()) {
831 throw std::length_error{"size() >= max_size()"};
832 }
833
834 reserve(elementCount + 1);
835
836 const size_type bucketBegin = getBucketIndexOfHash(hash(k));
837 const size_type bucketExtent = bucketExtents[bucketBegin];
838 const size_type bucketEnd = getWrappedIndex(bucketBegin + bucketExtent);
839 for (size_type index = bucketBegin; index != bucketEnd; index = getWrappedIndex(index + 1)) {
840 if (isActive(index) && equal(keys[index], k)) {
841 return {iterator{this, index}, false};
842 }
843 }
844 size_type index = bucketBegin;
845 size_type newBucketExtent = 1;
846 while (isActive(index)) {
847 index = getWrappedIndex(index + 1);
848 if (newBucketExtent >= size_type{std::numeric_limits<std::uint32_t>::max()}) {
849 throw std::length_error{"Maximum bucket size exceeded."};
850 }
851 ++newBucketExtent;
852 }
853
854 KeyAllocator keyAllocator = allocator;
855 ValueAllocator valueAllocator = allocator;
856 std::allocator_traits<KeyAllocator>::construct(keyAllocator, std::to_address(keys) + index, std::forward<K>(k));
857 try {
858 std::allocator_traits<ValueAllocator>::construct(valueAllocator, std::to_address(values) + index, std::forward<Args>(args)...);
859 } catch (...) {
860 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
861 throw;
862 }
863
864 if (newBucketExtent > bucketExtent) {
865 bucketExtents[bucketBegin] = static_cast<std::uint32_t>(newBucketExtent);
866 }
867 setActive(index);
868 ++elementCount;
869
870 return {iterator{this, index}, true};
871 }
872
873 [[nodiscard]] size_type eraseAtIndex(size_type index) {
874 GREM_ASSERT(index < elementCapacity);
875 GREM_ASSERT(isActive(index));
876
877 const size_type bucketBegin = getBucketIndexOfHash(hash(keys[index]));
878 size_type bucketExtent = bucketExtents[bucketBegin];
879 size_type bucketEnd = getWrappedIndex(bucketBegin + bucketExtent);
880 GREM_ASSERT(bucketExtent > 0);
881 GREM_ASSERT(bucketBegin != bucketEnd);
882 GREM_ASSERT(index != bucketEnd);
883
884 KeyAllocator keyAllocator = allocator;
885 ValueAllocator valueAllocator = allocator;
886 std::allocator_traits<ValueAllocator>::destroy(valueAllocator, std::to_address(values) + index);
887 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
888 clearActive(index);
889 --elementCount;
890
891 if (getWrappedIndex(index + 1) == bucketEnd) {
892 --bucketExtent;
893 bucketEnd = index;
894 while (bucketExtent > 0) {
895 const size_type previousIndex = getWrappedIndex(bucketEnd - 1);
896 if (isActive(previousIndex)) {
897 break;
898 }
899 --bucketExtent;
900 bucketEnd = previousIndex;
901 }
902 bucketExtents[bucketBegin] = static_cast<std::uint32_t>(bucketExtent);
903 }
904
905 return findActiveIndexUnbounded(index + 1);
906 }
907
908 template <typename K>
909 [[nodiscard]] size_type eraseKey(const K& k) {
910 if (empty()) {
911 return 0;
912 }
913
914 const size_type bucketBegin = getBucketIndexOfHash(hash(k));
915 size_type bucketExtent = bucketExtents[bucketBegin];
916 size_type bucketEnd = getWrappedIndex(bucketBegin + bucketExtent);
917 size_type index = bucketBegin;
918 while (index != bucketEnd && (!isActive(index) || !equal(keys[index], k))) {
919 index = getWrappedIndex(index + 1);
920 }
921 if (index == bucketEnd) {
922 return 0;
923 }
924
925 GREM_ASSERT(bucketExtent > 0);
926 GREM_ASSERT(bucketBegin != bucketEnd);
927
928 KeyAllocator keyAllocator = allocator;
929 ValueAllocator valueAllocator = allocator;
930 std::allocator_traits<ValueAllocator>::destroy(valueAllocator, std::to_address(values) + index);
931 std::allocator_traits<KeyAllocator>::destroy(keyAllocator, std::to_address(keys) + index);
932 clearActive(index);
933 --elementCount;
934
935 if (getWrappedIndex(index + 1) == bucketEnd) {
936 --bucketExtent;
937 bucketEnd = index;
938 while (bucketExtent > 0) {
939 const size_type previousIndex = getWrappedIndex(bucketEnd - 1);
940 if (isActive(previousIndex)) {
941 break;
942 }
943 --bucketExtent;
944 bucketEnd = previousIndex;
945 }
946 bucketExtents[bucketBegin] = static_cast<std::uint32_t>(bucketExtent);
947 }
948
949 return 1;
950 }
951
952 template <typename K>
953 [[nodiscard]] size_type findIndex(const K& k) const {
954 if (!empty()) {
955 const size_type bucketBegin = getBucketIndexOfHash(hash(k));
956 const size_type bucketExtent = bucketExtents[bucketBegin];
957 const size_type bucketEnd = getWrappedIndex(bucketBegin + bucketExtent);
958 size_type index = bucketBegin;
959 while (index != bucketEnd && (!isActive(index) || !equal(keys[index], k))) {
960 index = getWrappedIndex(index + 1);
961 }
962 if (index != bucketEnd) {
963 return index;
964 }
965 }
966 return elementCapacity;
967 }
968
969 typename std::allocator_traits<UInt64Allocator>::pointer activeBits{};
970 typename std::allocator_traits<UInt32Allocator>::pointer bucketExtents{};
971 typename std::allocator_traits<KeyAllocator>::pointer keys{};
972 typename std::allocator_traits<ValueAllocator>::pointer values{};
973 size_type elementCount = 0;
974 size_type elementCapacity = 0;
975 [[no_unique_address]] hasher hash;
976 [[no_unique_address]] key_equal equal;
977 [[no_unique_address]] Allocator allocator;
978};
979
980} // namespace grem
981
982namespace grem::pmr {
983
984template <typename Key, typename T, typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key>>
986
987} // namespace grem::pmr
988
989#endif
#define GREM_ASSERT(expression)
Definition assertions.hpp:77
Definition HashMap.hpp:30
KeyEqual key_equal
Definition HashMap.hpp:42
std::size_t size_type
Definition HashMap.hpp:40
constexpr hasher hash_function() const
Definition HashMap.hpp:530
constexpr HashMap(std::initializer_list< value_type > ilist, size_type bucket_count, const Hash &hash=Hash(), const Allocator &allocator=Allocator())
Definition HashMap.hpp:177
constexpr size_type count(const K &x) const
Definition HashMap.hpp:622
constexpr HashMap & operator=(HashMap &&other) noexcept
Definition HashMap.hpp:279
friend constexpr void swap(HashMap &a, HashMap &b) noexcept(noexcept(a.swap(b)))
Definition HashMap.hpp:341
constexpr bool operator==(const HashMap &other) const
Definition HashMap.hpp:724
constexpr Pair< iterator, bool > insert(P &&value)
Definition HashMap.hpp:425
constexpr HashMap(std::initializer_list< value_type > ilist, size_type bucket_count=0, const Hash &hash=Hash(), const KeyEqual &equal=KeyEqual(), const Allocator &allocator=Allocator())
Definition HashMap.hpp:170
constexpr const_iterator begin() const noexcept
Definition HashMap.hpp:704
constexpr size_type erase(K &&x)
Definition HashMap.hpp:512
constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count=0, const Hash &hash=Hash(), const KeyEqual &equal=KeyEqual(), const Allocator &allocator=Allocator())
Definition HashMap.hpp:156
constexpr const_iterator find(const K &x) const
Definition HashMap.hpp:640
constexpr ~HashMap()
Definition HashMap.hpp:225
constexpr void insert(InputIterator first, Sentinel last)
Definition HashMap.hpp:430
constexpr Pair< iterator, iterator > equal_range(const Key &key)
Definition HashMap.hpp:666
constexpr HashMap & operator=(const HashMap &other)
Definition HashMap.hpp:229
constexpr bool operator>=(const HashMap &other) const
Definition HashMap.hpp:740
Allocator allocator_type
Definition HashMap.hpp:43
constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count, const Hash &hash, const Allocator &allocator)
Definition HashMap.hpp:167
constexpr T & operator[](K &&x)
Definition HashMap.hpp:604
T mapped_type
Definition HashMap.hpp:39
constexpr size_type max_size() const noexcept
Definition HashMap.hpp:550
constexpr Pair< iterator, bool > insert_or_assign(const Key &k, M &&obj)
Definition HashMap.hpp:470
constexpr HashMap(std::initializer_list< value_type > ilist, size_type bucket_count, const Allocator &allocator=Allocator())
Definition HashMap.hpp:174
constexpr Pair< iterator, bool > insert_or_assign(K &&k, M &&obj)
Definition HashMap.hpp:488
constexpr HashMap(size_type bucket_count, const Allocator &allocator)
Definition HashMap.hpp:146
typename const_iterator::pointer const_pointer
Definition HashMap.hpp:136
constexpr const T & at(const Key &key) const
Definition HashMap.hpp:572
constexpr bool contains(const K &x) const
Definition HashMap.hpp:613
constexpr const_iterator cend() const noexcept
Definition HashMap.hpp:720
constexpr size_type erase(const Key &key)
Definition HashMap.hpp:507
constexpr void insert_range(R &&r)
Definition HashMap.hpp:444
constexpr void insert(std::initializer_list< value_type > ilist)
Definition HashMap.hpp:439
constexpr key_equal key_eq() const
Definition HashMap.hpp:534
constexpr bool operator<=(const HashMap &other) const
Definition HashMap.hpp:732
constexpr const T & at(const K &key) const
Definition HashMap.hpp:588
constexpr size_type size() const noexcept
Definition HashMap.hpp:546
constexpr Pair< iterator, bool > try_emplace(const Key &k, Args &&... args)
Definition HashMap.hpp:454
constexpr T & operator[](Key &&key)
Definition HashMap.hpp:599
constexpr HashMap(const HashMap &other, const Allocator &allocator)
Definition HashMap.hpp:183
constexpr const_iterator end() const noexcept
Definition HashMap.hpp:716
constexpr HashMap(HashMap &&other, const Allocator &allocator) noexcept
Definition HashMap.hpp:199
constexpr const_reference getAtIndex(size_type index) const
Definition HashMap.hpp:660
constexpr HashMap(const HashMap &other)
Definition HashMap.hpp:180
Hash hasher
Definition HashMap.hpp:41
constexpr void swap(HashMap &other) noexcept(std::allocator_traits< Allocator >::is_always_equal::value)
Definition HashMap.hpp:321
constexpr bool empty() const noexcept
Definition HashMap.hpp:542
typename iterator::difference_type difference_type
Definition HashMap.hpp:137
constexpr Pair< iterator, iterator > equal_range(const K &x)
Definition HashMap.hpp:683
friend constexpr size_type erase_if(HashMap &c, Predicate predicate)
Definition HashMap.hpp:517
constexpr T & operator[](const Key &key)
Definition HashMap.hpp:595
constexpr void clear() noexcept
Definition HashMap.hpp:345
constexpr bool operator<(const HashMap &other) const
Definition HashMap.hpp:728
constexpr bool contains(const Key &key) const
Definition HashMap.hpp:608
constexpr Pair< const_iterator, const_iterator > equal_range(const K &x) const
Definition HashMap.hpp:692
constexpr HashMap() noexcept=default
constexpr allocator_type get_allocator() const noexcept
Definition HashMap.hpp:538
constexpr void reserve(size_type capacity)
Definition HashMap.hpp:361
constexpr iterator erase(const_iterator pos)
Definition HashMap.hpp:496
constexpr HashMap(const Allocator &allocator)
Definition HashMap.hpp:152
constexpr const_iterator find(const Key &key) const
Definition HashMap.hpp:630
constexpr Pair< iterator, bool > try_emplace(K &&k, Args &&... args)
Definition HashMap.hpp:464
constexpr T & at(const K &key)
Definition HashMap.hpp:580
constexpr HashMap(InputIterator first, Sentinel last, size_type bucket_count, const Allocator &allocator)
Definition HashMap.hpp:163
constexpr Pair< const_iterator, const_iterator > equal_range(const Key &key) const
Definition HashMap.hpp:674
constexpr Pair< iterator, bool > emplace(Args &&... args)
Definition HashMap.hpp:449
constexpr bool operator>(const HashMap &other) const
Definition HashMap.hpp:736
constexpr iterator find(const Key &key)
Definition HashMap.hpp:626
constexpr HashMap(HashMap &&other) noexcept
Definition HashMap.hpp:188
constexpr Pair< iterator, bool > try_emplace(Key &&k, Args &&... args)
Definition HashMap.hpp:459
constexpr HashMap(size_type bucket_count, const Hash &hash, const Allocator &allocator)
Definition HashMap.hpp:149
Iterator< true > const_iterator
Definition HashMap.hpp:131
constexpr T & at(const Key &key)
Definition HashMap.hpp:565
constexpr size_type count(const Key &key) const
Definition HashMap.hpp:617
constexpr iterator getIteratorAtIndex(size_type index)
Definition HashMap.hpp:644
constexpr iterator find(const K &x)
Definition HashMap.hpp:635
Iterator< false > iterator
Definition HashMap.hpp:130
constexpr const_iterator cbegin() const noexcept
Definition HashMap.hpp:708
constexpr const_iterator getIteratorAtIndex(size_type index) const
Definition HashMap.hpp:649
Key key_type
Definition HashMap.hpp:38
constexpr Pair< iterator, bool > insert(value_type &&value)
Definition HashMap.hpp:420
typename iterator::value_type value_type
Definition HashMap.hpp:132
constexpr reference getAtIndex(size_type index)
Definition HashMap.hpp:654
constexpr Pair< iterator, bool > insert_or_assign(Key &&k, M &&obj)
Definition HashMap.hpp:479
typename iterator::reference reference
Definition HashMap.hpp:133
constexpr Pair< iterator, bool > insert(const value_type &value)
Definition HashMap.hpp:416
typename const_iterator::reference const_reference
Definition HashMap.hpp:134
constexpr HashMap & operator=(std::initializer_list< value_type > ilist)
Definition HashMap.hpp:315
constexpr iterator erase(const_iterator first, const_iterator last)
Definition HashMap.hpp:500
Definition concepts.hpp:106
@ K
'k'
Definition keyboard.hpp:81
Definition aliases.hpp:18
Definition Allocation.hpp:554
grem::HashMap< Key, T, Hash, KeyEqual, std::pmr::polymorphic_allocator< Pair< const Key, T > > > HashMap
Definition HashMap.hpp:985
Definition aliases.hpp:9
constexpr bool equal(input_range auto &&rangeA, input_range auto &&rangeB)
Definition algorithms.hpp:358
Pair(T1, T2) -> Pair< T1, T2 >
Definition HashMap.hpp:57
reference ref
Definition HashMap.hpp:58
constexpr reference * operator->() noexcept
Definition HashMap.hpp:60
Definition Pair.hpp:53