Jolt Physics
A multi core friendly Game Physics Engine
Loading...
Searching...
No Matches
HashTable.h
Go to the documentation of this file.
1// Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
2// SPDX-FileCopyrightText: 2024 Jorrit Rouwe
3// SPDX-License-Identifier: MIT
4
5#pragma once
6
7#include <Jolt/Math/BVec16.h>
8
10
14template <class Key, class KeyValue, class HashTableDetail, class Hash, class KeyEqual>
16{
17public:
19 using value_type = KeyValue;
21 using difference_type = ptrdiff_t;
22
23private:
25 template <class Table, class Iterator>
26 class IteratorBase
27 {
28 public:
30 using difference_type = typename Table::difference_type;
31 using value_type = typename Table::value_type;
32 using iterator_category = std::forward_iterator_tag;
33
35 IteratorBase(const IteratorBase &inRHS) = default;
36
38 IteratorBase & operator = (const IteratorBase &inRHS) = default;
39
41 explicit IteratorBase(Table *inTable) :
42 mTable(inTable),
43 mIndex(0)
44 {
45 while (mIndex < mTable->mMaxSize && (mTable->mControl[mIndex] & cBucketUsed) == 0)
46 ++mIndex;
47 }
48
50 IteratorBase(Table *inTable, size_type inIndex) :
51 mTable(inTable),
52 mIndex(inIndex)
53 {
54 }
55
57 Iterator & operator ++ ()
58 {
59 JPH_ASSERT(IsValid());
60
61 do
62 {
63 ++mIndex;
64 }
65 while (mIndex < mTable->mMaxSize && (mTable->mControl[mIndex] & cBucketUsed) == 0);
66
67 return static_cast<Iterator &>(*this);
68 }
69
71 Iterator operator ++ (int)
72 {
73 Iterator result(mTable, mIndex);
74 ++(*this);
75 return result;
76 }
77
79 const KeyValue & operator * () const
80 {
81 JPH_ASSERT(IsValid());
82 return mTable->mData[mIndex];
83 }
84
86 const KeyValue * operator -> () const
87 {
88 JPH_ASSERT(IsValid());
89 return mTable->mData + mIndex;
90 }
91
93 bool operator == (const Iterator &inRHS) const
94 {
95 return mIndex == inRHS.mIndex && mTable == inRHS.mTable;
96 }
97
99 bool operator != (const Iterator &inRHS) const
100 {
101 return !(*this == inRHS);
102 }
103
105 bool IsValid() const
106 {
107 return mIndex < mTable->mMaxSize
108 && (mTable->mControl[mIndex] & cBucketUsed) != 0;
109 }
110
111 Table * mTable;
112 size_type mIndex;
113 };
114
116 void AllocateTable(size_type inMaxSize)
117 {
118 JPH_ASSERT(mData == nullptr);
119
120 mMaxSize = inMaxSize;
121 mMaxLoad = uint32((cMaxLoadFactorNumerator * inMaxSize) / cMaxLoadFactorDenominator);
122 size_type required_size = mMaxSize * (sizeof(KeyValue) + 1) + 15; // Add 15 bytes to mirror the first 15 bytes of the control values
123 if constexpr (cNeedsAlignedAllocate)
124 mData = reinterpret_cast<KeyValue *>(AlignedAllocate(required_size, alignof(KeyValue)));
125 else
126 mData = reinterpret_cast<KeyValue *>(Allocate(required_size));
127 mControl = reinterpret_cast<uint8 *>(mData + mMaxSize);
128 }
129
131 void CopyTable(const HashTable &inRHS)
132 {
133 if (inRHS.empty())
134 return;
135
136 AllocateTable(inRHS.mMaxSize);
137
138 // Copy control bytes
139 memcpy(mControl, inRHS.mControl, mMaxSize + 15);
140
141 // Copy elements
142 uint index = 0;
143 for (const uint8 *control = mControl, *control_end = mControl + mMaxSize; control != control_end; ++control, ++index)
144 if (*control & cBucketUsed)
145 ::new (mData + index) KeyValue(inRHS.mData[index]);
146 mSize = inRHS.mSize;
147 }
148
150 void GrowTable()
151 {
152 // Calculate new size
153 size_type new_max_size = max<size_type>(mMaxSize << 1, 16);
154 if (new_max_size < mMaxSize)
155 {
156 JPH_ASSERT(false, "Overflow in hash table size, can't grow!");
157 return;
158 }
159
160 // Move the old table to a temporary structure
161 size_type old_max_size = mMaxSize;
162 KeyValue *old_data = mData;
163 const uint8 *old_control = mControl;
164 mData = nullptr;
165 mControl = nullptr;
166 mSize = 0;
167 mMaxSize = 0;
168 mMaxLoad = 0;
169
170 // Allocate new table
171 AllocateTable(new_max_size);
172
173 // Reset all control bytes
174 memset(mControl, cBucketEmpty, mMaxSize + 15);
175
176 if (old_data != nullptr)
177 {
178 // Copy all elements from the old table
179 for (size_type i = 0; i < old_max_size; ++i)
180 if (old_control[i] & cBucketUsed)
181 {
182 size_type index;
183 KeyValue *element = old_data + i;
184 JPH_IF_ENABLE_ASSERTS(bool inserted =) InsertKey</* AllowDeleted= */ false>(HashTableDetail::sGetKey(*element), index);
185 JPH_ASSERT(inserted);
186 ::new (mData + index) KeyValue(std::move(*element));
187 element->~KeyValue();
188 }
189
190 // Free memory
191 if constexpr (cNeedsAlignedAllocate)
192 AlignedFree(old_data);
193 else
194 Free(old_data);
195 }
196 }
197
198protected:
200 KeyValue & GetElement(size_type inIndex) const
201 {
202 return mData[inIndex];
203 }
204
207 template <bool AllowDeleted = true>
208 bool InsertKey(const Key &inKey, size_type &outIndex)
209 {
210 // Ensure we have enough space
211 if (mSize + 1 >= mMaxLoad)
212 GrowTable();
213
214 // Calculate hash
215 uint64 hash_value = Hash { } (inKey);
216
217 // Split hash into control byte and index
218 uint8 control = cBucketUsed | uint8(hash_value);
219 size_type bucket_mask = mMaxSize - 1;
220 size_type index = size_type(hash_value >> 7) & bucket_mask;
221
222 BVec16 control16 = BVec16::sReplicate(control);
223 BVec16 bucket_empty = BVec16::sZero();
224 BVec16 bucket_deleted = BVec16::sReplicate(cBucketDeleted);
225
226 // Keeps track of the index of the first deleted bucket we found
227 constexpr size_type cNoDeleted = ~size_type(0);
228 size_type first_deleted_index = cNoDeleted;
229
230 // Linear probing
231 KeyEqual equal;
232 for (;;)
233 {
234 // Read 16 control values (note that we added 15 bytes at the end of the control values that mirror the first 15 bytes)
235 BVec16 control_bytes = BVec16::sLoadByte16(mControl + index);
236
237 // Check for the control value we're looking for
238 uint32 control_equal = uint32(BVec16::sEquals(control_bytes, control16).GetTrues());
239
240 // Check for empty buckets
241 uint32 control_empty = uint32(BVec16::sEquals(control_bytes, bucket_empty).GetTrues());
242
243 // Check if we're still scanning for deleted buckets
244 if constexpr (AllowDeleted)
245 if (first_deleted_index == cNoDeleted)
246 {
247 // Check if any buckets have been deleted, if so store the first one
248 uint32 control_deleted = uint32(BVec16::sEquals(control_bytes, bucket_deleted).GetTrues());
249 if (control_deleted != 0)
250 first_deleted_index = index + CountTrailingZeros(control_deleted);
251 }
252
253 // Index within the 16 buckets
254 size_type local_index = index;
255
256 // Loop while there's still buckets to process
257 while ((control_equal | control_empty) != 0)
258 {
259 // Get the index of the first bucket that is either equal or empty
260 uint first_equal = CountTrailingZeros(control_equal);
261 uint first_empty = CountTrailingZeros(control_empty);
262
263 // Check if we first found a bucket with equal control value before an empty bucket
264 if (first_equal < first_empty)
265 {
266 // Skip to the bucket
267 local_index += first_equal;
268
269 // Make sure that our index is not beyond the end of the table
270 local_index &= bucket_mask;
271
272 // We found a bucket with same control value
273 if (equal(HashTableDetail::sGetKey(mData[local_index]), inKey))
274 {
275 // Element already exists
276 outIndex = local_index;
277 return false;
278 }
279
280 // Skip past this bucket
281 local_index++;
282 uint shift = first_equal + 1;
283 control_equal >>= shift;
284 control_empty >>= shift;
285 }
286 else
287 {
288 // An empty bucket was found, we can insert a new item
289 JPH_ASSERT(control_empty != 0);
290
291 // Get the location of the first empty or deleted bucket
292 local_index += first_empty;
293 if constexpr (AllowDeleted)
294 if (first_deleted_index < local_index)
295 local_index = first_deleted_index;
296
297 // Make sure that our index is not beyond the end of the table
298 local_index &= bucket_mask;
299
300 // Update control byte
301 mControl[local_index] = control;
302 if (local_index < 15)
303 mControl[mMaxSize + local_index] = control; // Mirror the first 15 bytes at the end of the control values
304 ++mSize;
305
306 // Return index to newly allocated bucket
307 outIndex = local_index;
308 return true;
309 }
310 }
311
312 // Move to next batch of 16 buckets
313 index = (index + 16) & bucket_mask;
314 }
315 }
316
317public:
319 class iterator : public IteratorBase<HashTable, iterator>
320 {
321 using Base = IteratorBase<HashTable, iterator>;
322
323 public:
325 using reference = typename Base::value_type &;
326 using pointer = typename Base::value_type *;
327
329 explicit iterator(HashTable *inTable) : Base(inTable) { }
330 iterator(HashTable *inTable, size_type inIndex) : Base(inTable, inIndex) { }
331 iterator(const iterator &inIterator) : Base(inIterator) { }
332
334 iterator & operator = (const iterator &inRHS) { Base::operator = (inRHS); return *this; }
335
336 using Base::operator *;
337
339 KeyValue & operator * ()
340 {
341 JPH_ASSERT(this->IsValid());
342 return this->mTable->mData[this->mIndex];
343 }
344
345 using Base::operator ->;
346
348 KeyValue * operator -> ()
349 {
350 JPH_ASSERT(this->IsValid());
351 return this->mTable->mData + this->mIndex;
352 }
353 };
354
356 class const_iterator : public IteratorBase<const HashTable, const_iterator>
357 {
358 using Base = IteratorBase<const HashTable, const_iterator>;
359
360 public:
362 using reference = const typename Base::value_type &;
363 using pointer = const typename Base::value_type *;
364
366 explicit const_iterator(const HashTable *inTable) : Base(inTable) { }
367 const_iterator(const HashTable *inTable, size_type inIndex) : Base(inTable, inIndex) { }
368 const_iterator(const const_iterator &inRHS) : Base(inRHS) { }
369 const_iterator(const iterator &inIterator) : Base(inIterator.mTable, inIterator.mIndex) { }
370
372 const_iterator & operator = (const iterator &inRHS) { this->mTable = inRHS.mTable; this->mIndex = inRHS.mIndex; return *this; }
373 const_iterator & operator = (const const_iterator &inRHS) { Base::operator = (inRHS); return *this; }
374 };
375
377 HashTable() = default;
378
380 HashTable(const HashTable &inRHS)
381 {
382 CopyTable(inRHS);
383 }
384
386 HashTable(HashTable &&ioRHS) noexcept :
387 mData(ioRHS.mData),
388 mControl(ioRHS.mControl),
389 mSize(ioRHS.mSize),
390 mMaxSize(ioRHS.mMaxSize),
391 mMaxLoad(ioRHS.mMaxLoad)
392 {
393 ioRHS.mData = nullptr;
394 ioRHS.mControl = nullptr;
395 ioRHS.mSize = 0;
396 ioRHS.mMaxSize = 0;
397 ioRHS.mMaxLoad = 0;
398 }
399
402 {
403 if (this != &inRHS)
404 {
405 clear();
406
407 CopyTable(inRHS);
408 }
409
410 return *this;
411 }
412
415 {
416 clear();
417 }
418
420 void reserve(size_type inMaxSize)
421 {
422 // Calculate max size based on load factor
423 size_type max_size = GetNextPowerOf2(max<uint32>((cMaxLoadFactorDenominator * inMaxSize) / cMaxLoadFactorNumerator, 16));
424 if (max_size <= mMaxSize)
425 return;
426
427 // Allocate buffers
428 AllocateTable(max_size);
429
430 // Reset all control bytes
431 memset(mControl, cBucketEmpty, mMaxSize + 15);
432 }
433
435 void clear()
436 {
437 // Delete all elements
438 if constexpr (!std::is_trivially_destructible<KeyValue>())
439 if (!empty())
440 for (size_type i = 0; i < mMaxSize; ++i)
441 if (mControl[i] & cBucketUsed)
442 mData[i].~KeyValue();
443
444 if (mData != nullptr)
445 {
446 // Free memory
447 if constexpr (cNeedsAlignedAllocate)
448 AlignedFree(mData);
449 else
450 Free(mData);
451
452 // Reset members
453 mData = nullptr;
454 mControl = nullptr;
455 mSize = 0;
456 mMaxSize = 0;
457 mMaxLoad = 0;
458 }
459 }
460
463 {
464 return iterator(this);
465 }
466
469 {
470 return iterator(this, mMaxSize);
471 }
472
475 {
476 return const_iterator(this);
477 }
478
481 {
482 return const_iterator(this, mMaxSize);
483 }
484
487 {
488 return const_iterator(this);
489 }
490
493 {
494 return const_iterator(this, mMaxSize);
495 }
496
498 bool empty() const
499 {
500 return mSize == 0;
501 }
502
505 {
506 return mSize;
507 }
508
510 std::pair<iterator, bool> insert(const value_type &inValue)
511 {
512 size_type index;
513 bool inserted = InsertKey(HashTableDetail::sGetKey(inValue), index);
514 if (inserted)
515 ::new (mData + index) KeyValue(inValue);
516 return std::make_pair(iterator(this, index), inserted);
517 }
518
520 const_iterator find(const Key &inKey) const
521 {
522 // Check if we have any data
523 if (empty())
524 return cend();
525
526 // Calculate hash
527 uint64 hash_value = Hash { } (inKey);
528
529 // Split hash into control byte and index
530 uint8 control = cBucketUsed | uint8(hash_value);
531 size_type bucket_mask = mMaxSize - 1;
532 size_type index = size_type(hash_value >> 7) & bucket_mask;
533
534 BVec16 control16 = BVec16::sReplicate(control);
535 BVec16 bucket_empty = BVec16::sZero();
536
537 // Linear probing
538 KeyEqual equal;
539 for (;;)
540 {
541 // Read 16 control values (note that we added 15 bytes at the end of the control values that mirror the first 15 bytes)
542 BVec16 control_bytes = BVec16::sLoadByte16(mControl + index);
543
544 // Check for the control value we're looking for
545 uint32 control_equal = uint32(BVec16::sEquals(control_bytes, control16).GetTrues());
546
547 // Check for empty buckets
548 uint32 control_empty = uint32(BVec16::sEquals(control_bytes, bucket_empty).GetTrues());
549
550 // Index within the 16 buckets
551 size_type local_index = index;
552
553 // Loop while there's still buckets to process
554 while ((control_equal | control_empty) != 0)
555 {
556 // Get the index of the first bucket that is either equal or empty
557 uint first_equal = CountTrailingZeros(control_equal);
558 uint first_empty = CountTrailingZeros(control_empty);
559
560 // Check if we first found a bucket with equal control value before an empty bucket
561 if (first_equal < first_empty)
562 {
563 // Skip to the bucket
564 local_index += first_equal;
565
566 // Make sure that our index is not beyond the end of the table
567 local_index &= bucket_mask;
568
569 // We found a bucket with same control value
570 if (equal(HashTableDetail::sGetKey(mData[local_index]), inKey))
571 {
572 // Element found
573 return const_iterator(this, local_index);
574 }
575
576 // Skip past this bucket
577 local_index++;
578 uint shift = first_equal + 1;
579 control_equal >>= shift;
580 control_empty >>= shift;
581 }
582 else
583 {
584 // An empty bucket was found, we didn't find the element
585 JPH_ASSERT(control_empty != 0);
586 return cend();
587 }
588 }
589
590 // Move to next batch of 16 buckets
591 index = (index + 16) & bucket_mask;
592 }
593 }
594
596 void erase(const const_iterator &inIterator)
597 {
598 JPH_ASSERT(inIterator.IsValid());
599
600 // Mark the bucket as deleted
601 mControl[inIterator.mIndex] = cBucketDeleted;
602 if (inIterator.mIndex < 15)
603 mControl[inIterator.mIndex + mMaxSize] = cBucketDeleted;
604
605 // Destruct the element
606 mData[inIterator.mIndex].~KeyValue();
607
608 // Decrease size
609 --mSize;
610 }
611
613 size_type erase(const Key &inKey)
614 {
615 const_iterator it = find(inKey);
616 if (it == cend())
617 return 0;
618
619 erase(it);
620 return 1;
621 }
622
624 void swap(HashTable &ioRHS) noexcept
625 {
626 std::swap(mData, ioRHS.mData);
627 std::swap(mControl, ioRHS.mControl);
628 std::swap(mSize, ioRHS.mSize);
629 std::swap(mMaxSize, ioRHS.mMaxSize);
630 std::swap(mMaxLoad, ioRHS.mMaxLoad);
631 }
632
633private:
635 static constexpr bool cNeedsAlignedAllocate = alignof(KeyValue) > (JPH_CPU_ADDRESS_BITS == 32? 8 : 16);
636
638 static constexpr uint64 cMaxLoadFactorNumerator = 7;
639 static constexpr uint64 cMaxLoadFactorDenominator = 8;
640
642 static constexpr uint8 cBucketEmpty = 0;
643 static constexpr uint8 cBucketDeleted = 0x7f;
644 static constexpr uint8 cBucketUsed = 0x80; // Lowest 7 bits are lowest 7 bits of the hash value
645
647 KeyValue * mData = nullptr;
648
650 uint8 * mControl = nullptr;
651
653 size_type mSize = 0;
654
656 size_type mMaxSize = 0;
657
659 size_type mMaxLoad = 0;
660};
661
std::uint8_t uint8
Definition Core.h:447
std::uint64_t uint64
Definition Core.h:450
unsigned int uint
Definition Core.h:446
#define JPH_NAMESPACE_END
Definition Core.h:379
std::uint32_t uint32
Definition Core.h:449
#define JPH_NAMESPACE_BEGIN
Definition Core.h:373
#define JPH_IF_ENABLE_ASSERTS(...)
Definition IssueReporting.h:35
#define JPH_ASSERT(...)
Definition IssueReporting.h:33
uint CountTrailingZeros(uint32 inValue)
Compute number of trailing zero bits (how many low bits are zero)
Definition Math.h:95
uint32 GetNextPowerOf2(uint32 inValue)
Get the next higher power of 2 of a value, or the value itself if the value is already a power of 2.
Definition Math.h:182
AllocateFunction Allocate
Definition Memory.cpp:68
FreeFunction Free
Definition Memory.cpp:70
AlignedFreeFunction AlignedFree
Definition Memory.cpp:72
AlignedAllocateFunction AlignedAllocate
Definition Memory.cpp:71
A vector consisting of 16 bytes.
Definition BVec16.h:11
static JPH_INLINE BVec16 sZero()
Vector with all zeros.
Definition BVec16.inl:46
static JPH_INLINE BVec16 sEquals(BVec16Arg inV1, BVec16Arg inV2)
Equals (component wise), highest bit of each component that is set is considered true.
Definition BVec16.inl:83
static JPH_INLINE BVec16 sReplicate(uint8 inV)
Replicate int inV across all components.
Definition BVec16.inl:57
static JPH_INLINE BVec16 sLoadByte16(const uint8 *inV)
Load 16 bytes from memory.
Definition BVec16.inl:72
Const iterator.
Definition HashTable.h:357
const_iterator(const HashTable *inTable, size_type inIndex)
Definition HashTable.h:367
const_iterator & operator=(const iterator &inRHS)
Assignment.
Definition HashTable.h:372
const typename Base::value_type * pointer
Definition HashTable.h:363
const_iterator(const iterator &inIterator)
Definition HashTable.h:369
const_iterator(const HashTable *inTable)
Constructors.
Definition HashTable.h:366
const typename Base::value_type & reference
Properties.
Definition HashTable.h:362
const_iterator(const const_iterator &inRHS)
Definition HashTable.h:368
Non-const iterator.
Definition HashTable.h:320
typename Base::value_type * pointer
Definition HashTable.h:326
typename Base::value_type & reference
Properties.
Definition HashTable.h:325
KeyValue & operator*()
Non-const access to key value pair.
Definition HashTable.h:339
KeyValue * operator->()
Non-const access to key value pair.
Definition HashTable.h:348
iterator(HashTable *inTable)
Constructors.
Definition HashTable.h:329
iterator & operator=(const iterator &inRHS)
Assignment.
Definition HashTable.h:334
iterator(HashTable *inTable, size_type inIndex)
Definition HashTable.h:330
iterator(const iterator &inIterator)
Definition HashTable.h:331
Definition HashTable.h:16
void reserve(size_type inMaxSize)
Reserve memory for a certain number of elements.
Definition HashTable.h:420
ptrdiff_t difference_type
Definition HashTable.h:21
void clear()
Destroy the entire hash table.
Definition HashTable.h:435
KeyValue & GetElement(size_type inIndex) const
Get an element by index.
Definition HashTable.h:200
iterator end()
Iterator to one beyond last element.
Definition HashTable.h:468
HashTable(const HashTable &inRHS)
Copy constructor.
Definition HashTable.h:380
size_type size() const
Number of elements in the table.
Definition HashTable.h:504
HashTable()=default
Default constructor.
void swap(HashTable &ioRHS) noexcept
Swap the contents of two hash tables.
Definition HashTable.h:624
const_iterator cbegin() const
Iterator to first element.
Definition HashTable.h:486
~HashTable()
Destructor.
Definition HashTable.h:414
iterator begin()
Iterator to first element.
Definition HashTable.h:462
const_iterator end() const
Iterator to one beyond last element.
Definition HashTable.h:480
const_iterator find(const Key &inKey) const
Find an element, returns iterator to element or end() if not found.
Definition HashTable.h:520
const_iterator cend() const
Iterator to one beyond last element.
Definition HashTable.h:492
HashTable(HashTable &&ioRHS) noexcept
Move constructor.
Definition HashTable.h:386
KeyValue value_type
Properties.
Definition HashTable.h:19
bool InsertKey(const Key &inKey, size_type &outIndex)
Definition HashTable.h:208
uint32 size_type
Definition HashTable.h:20
bool empty() const
Check if there are no elements in the table.
Definition HashTable.h:498
std::pair< iterator, bool > insert(const value_type &inValue)
Insert a new element, returns iterator and if the element was inserted.
Definition HashTable.h:510
void erase(const const_iterator &inIterator)
Erase an element by iterator.
Definition HashTable.h:596
const_iterator begin() const
Iterator to first element.
Definition HashTable.h:474
size_type erase(const Key &inKey)
Erase an element by key.
Definition HashTable.h:613
HashTable & operator=(const HashTable &inRHS)
Assignment operator.
Definition HashTable.h:401
Definition Array.h:590
Fallback hash function that calls T::GetHash()
Definition HashCombine.h:59