AGX Dynamics 2.42.3.1
Loading...
Searching...
No Matches
QuadraticProbingHashTable.h
Go to the documentation of this file.
1/*
2Copyright 2007-2025. Algoryx Simulation AB.
3
4All AGX source code, intellectual property, documentation, sample code,
5tutorials, scene files and technical white papers, are copyrighted, proprietary
6and confidential material of Algoryx Simulation AB. You may not download, read,
7store, distribute, publish, copy or otherwise disseminate, use or expose this
8material unless having a written signed agreement with Algoryx Simulation AB, or having been
9advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10valid commercial license from Algoryx Simulation AB.
11
12Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13from using this software, unless otherwise stated in written agreements with
14Algoryx Simulation AB.
15*/
16
17#ifndef AGX_QUADRATIC_PROBING_HASH_TABLE_H
18#define AGX_QUADRATIC_PROBING_HASH_TABLE_H
19
20
21#include <agx/Math.h>
22#include <agx/agx.h>
23#include <agx/ref_ptr.h>
24
25#include <agx/HashFunction.h>
26#include <agx/Container.h>
27#include <agx/Allocator.h>
28
29#include <cstddef> // mostly for size_t
30
31#ifdef _MSC_VER
32# pragma warning(push)
33# pragma warning(disable: 6011) // Disable warningC6011: dereferencing nullptr pointer
34#endif
35
36
37namespace agx
38{
39
46 template <typename KeyT, typename DataT, typename HashT = HashFn<KeyT>, typename AllocatorT = ByteAllocator>
48 {
49 public:
50 typedef DataT value_type;
51 typedef KeyT key_type;
52 typedef HashT hash_fn_type;
53
54 private:
55 #define AGX_HASH_TABLE_MIN_SIZE 4
56
57 #define AGX_HASH_TABLE_GROW_THRESHOLD 0.8
58 #define AGX_HASH_TABLE_SHRINK_THRESHOLD 0.25
59 #define AGX_HASH_TABLE_GROW_FACTOR 2.0
60 #define AGX_HASH_TABLE_SHRINK_FACTOR 0.5
61 #define AGX_HASH_TABLE_SMOOTHING_FACTOR 0.8f
62 #define AGX_HASH_TABLE_MAX_PROBE_LENGTH 10
63
64 public:
65 class Bucket
66 {
67 public:
68 enum State
69 {
72 VALID
73 };
74
81 // std::pair<KeyT, DataT> pair;
82 KeyT first;
83 DataT second;
84
85 // Cast operator to std::pair
86 AGX_FORCE_INLINE operator std::pair<KeyT, DataT>() { return std::make_pair(first, second); }
87
89 {
90 }
91
93 {
94 if (&b == this)
95 return *this;
96
97 first = b.first;
98 second = b.second;
99 state = b.state;
100
101 return *this;
102 }
103
105 { return state >= ACTIVE; }
106
108 {
109 // prefetch( &state, agx::NTA );
110 return state == VALID;
111 }
112
114 {
115 return state;
116 }
117
118 #if 0
119 AGX_FORCE_INLINE bool isActive() const
120 { return (state & (VALID | ACTIVE)) != 0; }
121
122 AGX_FORCE_INLINE bool isValid() const
123 { return (state & VALID) != 0; }
124 #endif
125
126 private:
127 friend class QuadraticProbingHashTableImplementation<KeyT, DataT, HashT, AllocatorT>;
128 agx::UInt8 state;
129 };
130
131 public:
132
133 template<typename T>
135 {
136 public:
138
139 public:
141 AGX_FORCE_INLINE template_iterator() : m_hashTable(0), m_currentIndex(0) {}
142
143 AGX_FORCE_INLINE template_iterator(T* hashTable, size_t startIndex = 0) : m_hashTable(hashTable), m_currentIndex(startIndex-1)
144 { this->gotoNextElement(); }
145
148 {
150 constIt.m_hashTable = m_hashTable;
151 constIt.m_currentIndex = m_currentIndex;
152 return constIt;
153 }
154
156 {
157 this->gotoNextElement();
158 return *this;
159 }
160
162 {
163 size_t oldIndex = m_currentIndex;
164 this->gotoNextElement();
165
166 return template_iterator<T>(m_hashTable, oldIndex);
167 }
168
170 {
171 this->gotoPreviousElement();
172 return *this;
173 }
174
176 {
177 size_t oldIndex = m_currentIndex;
178 this->gotoPreviousElement();
179
180 return template_iterator<T>(m_hashTable, oldIndex);
181 }
182
184 { return this->m_currentIndex == rhs.m_currentIndex && this->m_hashTable == rhs.m_hashTable; }
185
187 { return this->m_currentIndex != rhs.m_currentIndex || this->m_hashTable != rhs.m_hashTable; }
188
190 {
191 agxAssert1(m_hashTable && m_currentIndex != m_hashTable->numBuckets(), "Can not dereference an invalid bucket!");
192 return m_hashTable->buckets()[m_currentIndex];
193 }
194
196 { return &(operator*()); }
197
198
200 {
201 m_hashTable = copy.m_hashTable;
202 m_currentIndex = copy.m_currentIndex;
203 return *this;
204 }
205
206 private:
207 AGX_FORCE_INLINE void gotoNextElement()
208 {
209 m_currentIndex++;
210 while (m_currentIndex < m_hashTable->numBuckets() && !m_hashTable->buckets()[m_currentIndex].isValid())
211 m_currentIndex++;
212 }
213
214 AGX_FORCE_INLINE void gotoPreviousElement()
215 {
216 m_currentIndex--;
217 while (!m_hashTable->buckets()[m_currentIndex].isValid())
218 m_currentIndex--;
219 }
220 private:
222 QuadraticProbingHashTableT* m_hashTable;
223 size_t m_currentIndex;
224 };
225
229
231 {
232 public:
234
235 public:
236
237 AGX_FORCE_INLINE insert_iterator() : iterator(), m_overwrite(false)
238 {
239 }
240
241 AGX_FORCE_INLINE insert_iterator(QuadraticProbingHashTableT* hashTable, size_t startIndex, bool overwrite) : iterator(hashTable, startIndex), m_overwrite(overwrite)
242 {
243 }
244
249 {
250 return m_overwrite;
251 }
252
253 private:
254 bool m_overwrite;
255 };
256
257
259 AGX_FORCE_INLINE QuadraticProbingHashTableImplementation(const AllocatorT& allocator = AllocatorT()) : m_smoothingAverage(0), m_maxProbeLength(0), m_allocator(allocator)
260 { m_allocator.setContainer(this); }
261
264 {
265 *this = other;
266 }
267
270 {
271 m_allocator = other.m_allocator;
272 m_allocator.setContainer(this);
273
274 this->clear(MAINTAIN_BUFFER);
275 this->reserve(other.size());
276
277 for (const_iterator it = other.begin(); it != other.end(); ++it)
278 this->insert(it->first, it->second);
279
280 return *this;
281 }
282
283
286 {
287 for (size_t i = 0; i < numBuckets(); ++i)
288 buckets()[i].~Bucket();
289
290 m_allocator.deallocateBytes(m_buffer, m_capacity * sizeof(Bucket));
291 }
292
293
299 AGX_FORCE_INLINE DataT& operator[](const KeyT& key )
300 {
301 iterator it = find( key );
302 if (it == end() ){
303 it = insert( key, value_type() );
304 }
305 return it->second;
306 }
307
308 AGX_FORCE_INLINE const DataT& operator[](const KeyT& key ) const
309 {
310 const_iterator it = find( key );
311 agxAssert( it != end() );
312 return it->second;
313 }
314
321 DataT& getOrCreate( const KeyT& key )
322 {
323 return (*this)[ key ];
324 }
325
330 insert_iterator insert(const KeyT& key, const DataT& data)
331 {
332 UInt32 hashValue = m_hashFunctor(key);
333 Bucket *bucket;
334 Bucket *targetBucket = 0;
335 size_t offset = 0;
336
337 /* Check if we should grow and rebuild hash table */
338 if (numFilled() >= (size_t)((float)numBuckets() * AGX_HASH_TABLE_GROW_THRESHOLD))
339 this->rebuild((size_t)((float)(numBuckets()+1) * AGX_HASH_TABLE_GROW_FACTOR));
340
341 /* Iterate until target bucket is found */
342 bool alwaysTrue = true;
343 do
344 {
345 bucket = &buckets()[(hashValue + offset * offset) % numBuckets()];
346
347 /* Check if inactive bucket or overwriting previous insertion with same key */
348 if (!bucket->isActive() || (bucket->isValid() && hashKeyEqual(bucket->first, key)))
349 {
350 targetBucket = bucket;
351 break;
352 }
353
354 /* Tag first free slot */
355 if (!bucket->isValid() && !targetBucket)
356 targetBucket = bucket;
357
358 /* If we have found a free bucket we can stop iterating when we are sure that the key was not previously inserted */
359 if (targetBucket && offset >= m_maxProbeLength)
360 break;
361
362 /* Go to next bucket */
363 offset++;
364
365 /* Resize and rebuild table if it takes too long to find a free slot */
367 {
368 this->rebuild((size_t)((float)numBuckets() * AGX_HASH_TABLE_GROW_FACTOR));
369 return this->insert(key, data);
370 }
371 } while (alwaysTrue);
372
373 agxAssert(targetBucket);
374
375 if (offset > m_maxProbeLength)
376 m_maxProbeLength = (UInt16)offset;
377
378
379 targetBucket->first = key;
380 targetBucket->second = data;
381
382
383 /* Check if inserting a new value rather than overwriting an old entry */
384 bool overwrite = targetBucket->isValid();
385 if (!overwrite)
386 {
387 numFilled()++;
388 targetBucket->state = Bucket::VALID;
389 }
390
391 return insert_iterator(this, targetBucket - buckets(), overwrite);
392 }
393
397 AGX_FORCE_INLINE bool contains(const KeyT& key) const
398 {
399 return this->findBucket(key) != numBuckets();
400 }
401
406 {
407 return iterator(this, this->findBucket(key));
408 }
409
410 AGX_FORCE_INLINE const_iterator find(const KeyT& key) const
411 {
412 return const_iterator(this, this->findBucket(key));
413 }
414
415
420 { return iterator(this); }
421
423 { return const_iterator(this); }
424
425
430 { return iterator(this, numBuckets()); }
431
433 { return const_iterator(this, numBuckets()); }
434
435
440 AGX_FORCE_INLINE bool erase(const KeyT& key)
441 {
442 return this->eraseBucket(this->findBucket(key));
443 }
444
450 {
451 this->eraseBucket(it.m_currentIndex);
452 return iterator(this, it.m_currentIndex);
453 }
454
459 {
460 if (policy == MAINTAIN_BUFFER)
461 {
462 for (size_t i = 0; i < numBuckets(); i++)
463 {
464 buckets()[i].first.~KeyT();
465 buckets()[i].second.~DataT();
466 ::new (&(buckets()[i])) Bucket();
467
468 //buckets()[i] = Bucket();
469 }
470 }
471 else if (policy == SHRINK_BUFFER)
472 {
473 for (size_t i = 0; i < numBuckets(); ++i)
474 buckets()[i].~Bucket();
475
476 m_allocator.deallocateBytes(m_buffer, m_capacity * sizeof(Bucket));
477 m_buffer = nullptr;
478 numBuckets() = 0;
479
480 m_smoothingAverage = 0.0;
481 }
482 else //if (policy == SHRINK_BUFFER_AVERAGED)
483 {
484 /* Smoothing average is never less than current size */
485 if ((Real32)numFilled() > m_smoothingAverage)
486 m_smoothingAverage = Real32(numFilled());
487
488 /* Update smoothing average */
489 m_smoothingAverage = Real32(AGX_HASH_TABLE_SMOOTHING_FACTOR * m_smoothingAverage + (1.0-AGX_HASH_TABLE_SMOOTHING_FACTOR) * (Real32)numFilled());
490
491 /* Reallocate buffer if the smoothing average is sufficiently below the current capacity */
492 if (m_smoothingAverage < AGX_HASH_TABLE_SHRINK_THRESHOLD * (float)numBuckets() && m_smoothingAverage >= AGX_HASH_TABLE_MIN_SIZE)
493 {
494 for (size_t i = 0; i < numBuckets(); ++i)
495 buckets()[i].~Bucket();
496
497 void *oldBuffer = m_buffer;
498 size_t oldCapacity = m_capacity;
499
500 numBuckets() = agx::nextPrime((int)m_smoothingAverage);
501 m_buffer = m_allocator.allocateBytes(numBuckets() * sizeof(Bucket));
502
503 for (size_t i = 0; i < numBuckets(); ++i)
504 ::new (&(buckets()[i])) Bucket();
505
506 m_allocator.deallocateBytes(oldBuffer, oldCapacity * sizeof(Bucket));
507 }
508 else
509 {
510 for (size_t i = 0; i < numBuckets(); i++)
511 {
512 buckets()[i].first.~KeyT();
513 buckets()[i].second.~DataT();
514 ::new (&(buckets()[i])) Bucket();
515 }
516 }
517 }
518
519
520 numFilled() = 0;
521 m_maxProbeLength = 0;
522 }
523
524
529 {
530 if (size <= (size_t)((float)numBuckets() * AGX_HASH_TABLE_GROW_THRESHOLD))
531 return;
532
533 this->rebuild((size_t)((float)size / AGX_HASH_TABLE_GROW_THRESHOLD));
534 }
535
542 template<typename T>
543 void purge(T purger)
544 {
545 for (size_t i = 0; i < numBuckets(); i++)
546 {
547 Bucket& bucket = buckets()[i];
548
549 if (bucket.isValid() && purger(bucket.first, bucket.second))
550 {
551 //bucket = Bucket();
552 bucket.first.~KeyT();
553 bucket.second.~DataT();
554 ::new (&bucket) Bucket();
555
556 bucket.state = Bucket::ACTIVE;
557 numFilled()--;
558 }
559 }
560
562 this->rebuild( size_t((float)numFilled() * AGX_HASH_TABLE_GROW_FACTOR) );
563 }
564
565 AllocatorT& allocator() { return m_allocator; }
566 const AllocatorT& allocator() const { return m_allocator; }
567
569 AGX_FORCE_INLINE size_t getNumActiveElements() const { return numBuckets(); }
571
572 public:
573 AGX_FORCE_INLINE const Bucket *getBucketBuffer() const { return buckets(); }
574 AGX_FORCE_INLINE size_t getMaxProbeLength() const { return m_maxProbeLength; }
575 AGX_FORCE_INLINE size_t getNumBuckets() const { return numBuckets(); }
576
577
578 protected:
579 template <typename T1, typename T2, typename T3>
580 friend class HashTableComponent;
581
582 // Access to Container members
584 AGX_FORCE_INLINE size_t& numFilled() { return m_size; }
585
586 AGX_FORCE_INLINE Bucket *buckets() const { return static_cast<Bucket *>(m_buffer); }
587 AGX_FORCE_INLINE size_t numBuckets() const { return m_capacity; }
588 AGX_FORCE_INLINE size_t numFilled() const { return m_size; }
589
590
594 void rebuild(size_t size)
595 {
596 size = std::max( size, size_t(AGX_HASH_TABLE_MIN_SIZE) );
597 //LOGGER_DEBUG() << "QuadraticProbingHashTable: Rebuilding and resizing from " << numBuckets() << " to " << agx::nextPrime((int)(numBuckets() * resizeFactor)) << " buckets.\n" << LOGGER_END();
599 size_t oldNumBuckets = numBuckets();
600 Bucket *oldBuckets = buckets();
601
602 // Do not set numBuckets directly, since allocateBytes might Throw an exception,
603 // after which we want to be able to recover.
604 const size_t desiredNumBuckets = (size_t)agx::nextPrime((int)size);
605 const size_t desiredNumBytes = desiredNumBuckets * sizeof(Bucket);
606
607 m_buffer = m_allocator.allocateBytes(desiredNumBytes);
608 for (size_t i = 0; i < desiredNumBuckets; ++i)
609 ::new (&(buckets()[i])) Bucket();
610
611 numBuckets() = desiredNumBuckets;
612
613 numFilled() = 0;
614 m_maxProbeLength = 0;
615
616 for (size_t i = 0; i < oldNumBuckets; i++)
617 {
618 Bucket& bucket = oldBuckets[i];
619
620 if (bucket.isValid())
621 this->insert(bucket.first, bucket.second);
622 }
623
624 for (size_t i = 0; i < oldNumBuckets; ++i)
625 oldBuckets[i].~Bucket();
626
627 m_allocator.deallocateBytes((void *)oldBuckets, oldNumBuckets * sizeof(Bucket));
628 }
629
630
631 template <typename T2>
632 AGX_FORCE_INLINE size_t findBucket(const T2& key) const
633 {
634 if (!buckets())
635 return numBuckets();
636
637 UInt32 hashValue = m_hashFunctor(key);
638 size_t index = hashValue % numBuckets();
639 const Bucket *bucket = &buckets()[index];
640
641 /* First test is outside for-loop, hopefully getting better branch prediction */
642 if (bucket->isValid() && hashKeyEqual(bucket->first, key))
643 return index;
644
645
646 for (size_t offset = 1; bucket->isActive() && offset <= m_maxProbeLength; offset++)
647 {
648 index = (hashValue + offset * offset) % numBuckets();
649 bucket = &buckets()[index];
650
651 if (bucket->isValid() && hashKeyEqual(bucket->first, key))
652 return index;
653 }
654
655 /* Not found */
656 return numBuckets();
657 }
658
659 bool eraseBucket(size_t index)
660 {
661 if (index >= numBuckets())
662 return false;
663
664 Bucket *bucket = &buckets()[index];
665 if (!bucket->isValid())
666 return false;
667
668 numFilled()--;
669
670 // Replace bucket by a new one (otherwise, if key or data is ref_ptr their ref count won't decrease)
671 bucket->first.~KeyT();
672 bucket->second.~DataT();
673 ::new (bucket) Bucket();
674
675 // Bucket does not become inactive since it might be in the middle of a probing chain
676 bucket->state = Bucket::ACTIVE;
677
678 return true;
679 }
680
681 private:
682 Real32 m_smoothingAverage;
683 UInt16 m_maxProbeLength;
684 AllocatorT m_allocator;
685 HashT m_hashFunctor;
686 };
687
688
689
697 template <typename KeyT, typename DataT, typename HashT = HashFn<KeyT>, typename AllocatorT = ByteAllocator>
698 class QuadraticProbingHashTable : public QuadraticProbingHashTableImplementation<KeyT, DataT, HashT, AllocatorT>
699 {
700 public:
702
704 {}
705
706 };
707
708 template <typename KeyT, typename DataT, typename HashT, typename AllocatorT>
709 class QuadraticProbingHashTable< agx::ref_ptr<KeyT>, DataT, HashT, AllocatorT > : public QuadraticProbingHashTableImplementation<agx::ref_ptr<KeyT>, DataT, HashT, AllocatorT>
710 {
711 public:
715
717 {}
718
720 AGX_FORCE_INLINE bool contains(const KeyT *key) const
721 {
722 return this->findBucket(key) != this->numBuckets();
723 }
724
726 AGX_FORCE_INLINE iterator find(const KeyT *key)
727 {
728 return iterator(this, this->findBucket(key));
729 }
730
731 AGX_FORCE_INLINE const_iterator find(const KeyT *key) const
732 {
733 return const_iterator(this, this->findBucket(key));
734 }
735
737 AGX_FORCE_INLINE bool erase(const KeyT *key)
738 {
739 return this->eraseBucket(this->findBucket(key));
740 }
741
742 };
743
744}
745
746#ifdef _MSC_VER
747# pragma warning(pop)
748#endif
749
750#endif
#define AGX_HASH_TABLE_GROW_FACTOR
#define AGX_HASH_TABLE_GROW_THRESHOLD
#define AGX_HASH_TABLE_MAX_PROBE_LENGTH
#define AGX_HASH_TABLE_SHRINK_THRESHOLD
#define AGX_HASH_TABLE_MIN_SIZE
#define AGX_HASH_TABLE_SHRINK_FACTOR
#define AGX_HASH_TABLE_SMOOTHING_FACTOR
The Container is the base class for several of the container classes proided by AGX,...
Definition: Container.h:35
size_t m_size
Definition: Container.h:94
size_t m_capacity
Definition: Container.h:95
ClearPolicy
agxData::Values from this enumeration is passed to the subclasses' 'clear' method in order to control...
Definition: Container.h:43
@ SHRINK_BUFFER
Buffer is deallocated and replaced by an newly allocated empty buffer.
Definition: Container.h:44
@ MAINTAIN_BUFFER
Buffer is maintained (normal stl behavior).
Definition: Container.h:46
@ SHRINK_BUFFER_AVERAGED
Buffer is shrunk if a smoothing average (which is updated each clear call) goes below a threshold.
Definition: Container.h:45
void * m_buffer
Definition: Container.h:96
size_t size() const
Definition: Container.h:134
KeyT first
We used to wrap key,data in a std::pair.
insert_iterator(QuadraticProbingHashTableT *hashTable, size_t startIndex, bool overwrite)
template_iterator< T > & operator=(const template_iterator< T > &copy)
A simple hash table using quadratic probing.
iterator begin()
Iterator to first element in hash table.
bool erase(const KeyT &key)
Erase an element from the hash table.
void clear(ClearPolicy policy=SHRINK_BUFFER_AVERAGED)
Remove all elements.
iterator erase(const iterator &it)
Erase an element using an iterator.
DataT & getOrCreate(const KeyT &key)
Returns value given key.
bool contains(const KeyT &key) const
Boolean query to test existence of an element.
iterator find(const KeyT &key)
Find an element.
DataT & operator[](const KeyT &key)
Index operator for accessing elements in the hash, inserting it if not found.
const_iterator find(const KeyT &key) const
QuadraticProbingHashTableImplementation(const AllocatorT &allocator=AllocatorT())
Constructor.
insert_iterator insert(const KeyT &key, const DataT &data)
Insert an element, overwriting if key already exists.
template_iterator< const QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > > const_iterator
const DataT & operator[](const KeyT &key) const
QuadraticProbingHashTableImplementation(const QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > &other)
Copy constructor.
void reserve(size_t size)
Reserve capacity in the hash table.
iterator end()
Iterator marking end of hash table.
template_iterator< QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > > iterator
Iterators.
void rebuild(size_t size)
Rebuild, and optionally resize hash table.
QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > & operator=(const QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > &other)
Assignment operator.
QuadraticProbingHashTableImplementation< agx::ref_ptr< KeyT >, DataT, HashT, AllocatorT > Implementation
Inheritance with partial specialization due to bug with ref_ptr containers.
QuadraticProbingHashTable(const AllocatorT &allocator=AllocatorT())
QuadraticProbingHashTableImplementation< KeyT, DataT, HashT, AllocatorT > Implementation
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:30
#define agxAssert1(expr, msg)
Definition: debug.h:144
#define agxAssert(expr)
Definition: debug.h:143
#define DOXYGEN_END_INTERNAL_BLOCK()
Definition: macros.h:89
#define DOXYGEN_START_INTERNAL_BLOCK()
Definition: macros.h:88
#define AGX_FORCE_INLINE
Definition: macros.h:58
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
uint16_t UInt16
Definition: Integer.h:31
uint32_t UInt32
Definition: Integer.h:32
AGXCORE_EXPORT int nextPrime(int n)
uint8_t UInt8
Definition: Integer.h:30
float Real32
Definition: Real.h:43
bool hashKeyEqual(const T1 &key1, const T2 &key2)
Definition: HashFunction.h:177