AGX Dynamics  2.35.0.1
LinearProbingHashSet.h
Go to the documentation of this file.
1 /*
2 Copyright 2007-2022. Algoryx Simulation AB.
3 
4 All AGX source code, intellectual property, documentation, sample code,
5 tutorials, scene files and technical white papers, are copyrighted, proprietary
6 and confidential material of Algoryx Simulation AB. You may not download, read,
7 store, distribute, publish, copy or otherwise disseminate, use or expose this
8 material unless having a written signed agreement with Algoryx Simulation AB, or having been
9 advised so by Algoryx Simulation AB for a time limited evaluation, or having purchased a
10 valid commercial license from Algoryx Simulation AB.
11 
12 Algoryx Simulation AB disclaims all responsibilities for loss or damage caused
13 from using this software, unless otherwise stated in written agreements with
14 Algoryx Simulation AB.
15 */
16 
17 
18 // Inspired by Emil Ernerfeldt:
19 // https://github.com/emilk/emilib/tree/master/emilib
20 // LICENSE:
21 // This software is dual-licensed to the public domain and under the following
22 // license: you are granted a perpetual, irrevocable license to copy, modify,
23 // publish, and distribute this file as you see fit.
24 
25 
26 
27 
28 #pragma once
29 
30 #include <cstdlib>
31 #include <iterator>
32 #include <utility>
33 
34 #include <agx/ref_ptr.h>
35 #include <agx/hash.h>
36 
37 namespace agx
38 {
42  template <typename KeyT, typename HashT = agx::HashFn<KeyT>>
44  {
45  private:
47  enum class State : uint8_t
48  {
49  INACTIVE, // Never been touched
50  ACTIVE, // Is inside a search-chain, but is empty
51  FILLED // Is set with key/value
52  };
53 
54  public:
55  using size_type = size_t;
56  using value_type = KeyT;
57  using reference = KeyT&;
58  using const_reference = const KeyT&;
59 
60  class iterator
61  {
62  public:
63  using iterator_category = std::forward_iterator_tag;
64  using difference_type = size_t;
65  using distance_type = size_t;
66  using value_type = KeyT;
67  using pointer = value_type*;
69 
71  {
72  }
73 
74  iterator(MyType* hash_set, size_t bucket) : _set(hash_set), _bucket(bucket)
75  {
76  }
77 
79  {
80  this->goto_next_element();
81  return *this;
82  }
83 
85  {
86  size_t old_index = _bucket;
87  this->goto_next_element();
88  return iterator(_set, old_index);
89  }
90 
92  {
93  return _set->_keys[_bucket];
94  }
95 
97  {
98  return _set->_keys + _bucket;
99  }
100 
101  bool operator==(const iterator& rhs)
102  {
103  agxAssert(_set == rhs._set);
104  return this->_bucket == rhs._bucket;
105  }
106 
107  bool operator!=(const iterator& rhs)
108  {
109  agxAssert(_set == rhs._set);
110  return this->_bucket != rhs._bucket;
111  }
112 
113  private:
114  void goto_next_element()
115  {
116  agxAssert(_bucket < _set->_num_buckets);
117  do {
118  _bucket++;
119  } while (_bucket < _set->_num_buckets && _set->_states[_bucket] != State::FILLED);
120  }
121 
122  //private:
123  // friend class MyType;
124  public:
126  size_t _bucket;
127  };
128 
130  {
131  public:
132  using iterator_category = std::forward_iterator_tag;
133  using difference_type = size_t;
134  using distance_type = size_t;
135  using value_type = const KeyT;
136  using pointer = value_type*;
138 
140 
141  const_iterator(iterator proto) : _set(proto._set), _bucket(proto._bucket)
142  {
143  }
144 
145  const_iterator(const MyType* hash_set, size_t bucket) : _set(hash_set), _bucket(bucket)
146  {
147  }
148 
150  {
151  this->goto_next_element();
152  return *this;
153  }
154 
156  {
157  size_t old_index = _bucket;
158  this->goto_next_element();
159  return const_iterator(_set, old_index);
160  }
161 
163  {
164  return _set->_keys[_bucket];
165  }
166 
168  {
169  return _set->_keys + _bucket;
170  }
171 
172  bool operator==(const const_iterator& rhs)
173  {
174  agxAssert(_set == rhs._set);
175  return this->_bucket == rhs._bucket;
176  }
177 
178  bool operator!=(const const_iterator& rhs)
179  {
180  agxAssert(_set == rhs._set);
181  return this->_bucket != rhs._bucket;
182  }
183 
184  private:
185  void goto_next_element()
186  {
187  agxAssert(_bucket < _set->_num_buckets);
188  do {
189  _bucket++;
190  } while (_bucket < _set->_num_buckets && _set->_states[_bucket] != State::FILLED);
191  }
192 
193  //private:
194  // friend class MyType;
195  public:
196  const MyType* _set;
197  size_t _bucket;
198  };
199 
200 
201  class insert_iterator : public iterator
202  {
203  public:
204  insert_iterator() : iterator(), m_overwrite(false)
205  {
206  }
207 
208  insert_iterator(MyType* hash_set, size_t bucket, bool overwrite)
209  : iterator(hash_set, bucket)
210  , m_overwrite(overwrite)
211  {
212  }
213 
217  bool didOverwrite() const
218  {
219  return m_overwrite;
220  }
221 
222  private:
223  bool m_overwrite;
224  };
225 
226  // ------------------------------------------------------------------------
227 
229 
231  {
232  reserve(other.size());
233  insert(cbegin(other), cend(other));
234  }
235 
237  {
238  *this = std::move(other);
239  }
240 
242  {
243  clear();
244  reserve(other.size());
245  insert(cbegin(other), cend(other));
246  return *this;
247  }
248 
250  {
251  this->swap(other);
252  return *this;
253  }
254 
256  {
257  for (size_t bucket=0; bucket<_num_buckets; ++bucket) {
258  if (_states[bucket] == State::FILLED) {
259  _keys[bucket].~KeyT();
260  }
261  }
262  free(_states);
263  free(_keys);
264  }
265 
267  {
268  std::swap(_hasher, other._hasher);
269  std::swap(_states, other._states);
270  std::swap(_keys, other._keys);
271  std::swap(_num_buckets, other._num_buckets);
272  std::swap(_num_filled, other._num_filled);
273  std::swap(_max_probe_length, other._max_probe_length);
274  std::swap(_mask, other._mask);
275  }
276 
277  // -------------------------------------------------------------
278 
280  {
281  size_t bucket = 0;
282  while (bucket<_num_buckets && _states[bucket] != State::FILLED) {
283  ++bucket;
284  }
285  return iterator(this, bucket);
286  }
287 
289  {
290  size_t bucket = 0;
291  while (bucket<_num_buckets && _states[bucket] != State::FILLED) {
292  ++bucket;
293  }
294  return const_iterator(this, bucket);
295  }
296 
298  { return iterator(this, _num_buckets); }
299 
301  { return const_iterator(this, _num_buckets); }
302 
303  size_t size() const
304  {
305  return _num_filled;
306  }
307 
308  bool empty() const
309  {
310  return _num_filled==0;
311  }
312 
313  // ------------------------------------------------------------
314 
315  iterator find(const KeyT& key)
316  {
317  auto bucket = this->find_filled_bucket(key);
318  if (bucket == (size_t)-1) {
319  return this->end();
320  }
321  return iterator(this, bucket);
322  }
323 
324  const_iterator find(const KeyT& key) const
325  {
326  auto bucket = this->find_filled_bucket(key);
327  if (bucket == (size_t)-1) {
328  return this->end();
329  }
330  return const_iterator(this, bucket);
331  }
332 
333  bool contains(const KeyT& k) const
334  {
335  return find_filled_bucket(k) != (size_t)-1;
336  }
337 
338  size_t count(const KeyT& k) const
339  {
340  return find_filled_bucket(k) != (size_t)-1 ? 1 : 0;
341  }
342 
343  // -----------------------------------------------------
344 
345  // Insert an element, unless it already exists.
346  // Returns a pair consisting of an iterator to the inserted element
347  // (or to the element that prevented the insertion)
348  // and a bool denoting whether the insertion took place.
349  insert_iterator insert(const KeyT& key)
350  {
351  check_expand_need();
352 
353  auto bucket = find_or_allocate(key);
354 
355  if (_states[bucket] == State::FILLED) {
356  _keys[bucket] = key;
357  return insert_iterator(this, bucket, true);
358  } else {
359  _states[bucket] = State::FILLED;
360  new(_keys + bucket) KeyT(key);
361  _num_filled++;
362  return insert_iterator(this, bucket, false);
363  }
364  }
365 
366  // Insert an element, unless it already exists.
367  // Returns a pair consisting of an iterator to the inserted element
368  // (or to the element that prevented the insertion)
369  // and a bool denoting whether the insertion took place.
371  {
372  check_expand_need();
373 
374  auto bucket = find_or_allocate(key);
375 
376  if (_states[bucket] == State::FILLED) {
377  _keys[bucket] = std::move(key);
378  return insert_iterator(this, bucket, true);
379  } else {
380  _states[bucket] = State::FILLED;
381  new(_keys + bucket) KeyT(std::move(key));
382  _num_filled++;
383  return insert_iterator(this, bucket, false);
384  }
385  }
386 
387  template<class... Args>
388  insert_iterator emplace(Args&&... args)
389  {
390  return insert(KeyT(std::forward<Args>(args)...));
391  }
392 
394  {
395  for (; begin != end; ++begin) {
396  insert(*begin);
397  }
398  }
399 
400  // Same as above, but contains(key) MUST be false
401  void insert_unique(KeyT&& key)
402  {
403  agxAssert(!contains(key));
404  check_expand_need();
405  auto bucket = find_empty_bucket(key);
406  _states[bucket] = State::FILLED;
407  new(_keys + bucket) KeyT(std::move(key));
408  _num_filled++;
409  }
410 
411  // -------------------------------------------------------
412 
413  /* Erase an element from the hash set.
414  return false if element was not found */
415  bool erase(const KeyT& key)
416  {
417  auto bucket = find_filled_bucket(key);
418  if (bucket != (size_t)-1) {
419  erase_bucket(bucket);
420  return true;
421  } else {
422  return false;
423  }
424  }
425 
426  /* Erase an element using an iterator.
427  Returns an iterator to the next element (or end()). */
429  {
430  agxAssert(it._set == this);
431  agxAssert(it._bucket < _num_buckets);
432  erase_bucket(it._bucket);
433  return ++it;
434  }
435 
436  // Remove all elements, keeping full capacity.
437  void clear()
438  {
439  for (size_t bucket=0; bucket<_num_buckets; ++bucket) {
440  if (_states[bucket] == State::FILLED) {
441  _states[bucket] = State::INACTIVE;
442  _keys[bucket].~KeyT();
443  }
444  }
445  _num_filled = 0;
446  _max_probe_length = -1;
447  }
448 
449  // Make room for this many elements
450  void reserve(size_t num_elems)
451  {
452  size_t required_buckets = num_elems + num_elems/2 + 1;
453  if (required_buckets <= _num_buckets) {
454  return;
455  }
456  size_t num_buckets = 4;
457  while (num_buckets < required_buckets) { num_buckets *= 2; }
458 
459  auto new_states = (State*)malloc(num_buckets * sizeof(State));
460  auto new_keys = (KeyT*)malloc(num_buckets * sizeof(KeyT));
461 
462  if (!new_states || !new_keys) {
463  free(new_states);
464  free(new_keys);
465  throw std::bad_alloc();
466  }
467 
468  // auto old_num_filled = _num_filled;
469  auto old_num_buckets = _num_buckets;
470  auto old_states = _states;
471  auto old_keys = _keys;
472 
473  _num_filled = 0;
474  _num_buckets = num_buckets;
475  _mask = _num_buckets - 1;
476  _states = new_states;
477  _keys = new_keys;
478 
479  std::fill_n(_states, num_buckets, State::INACTIVE);
480 
481  _max_probe_length = -1;
482 
483  for (size_t src_bucket=0; src_bucket<old_num_buckets; src_bucket++) {
484  if (old_states[src_bucket] == State::FILLED) {
485  auto& src = old_keys[src_bucket];
486 
487  auto dst_bucket = find_empty_bucket(src);
488  agxAssert(dst_bucket != (size_t)-1);
489  agxAssert(_states[dst_bucket] != State::FILLED);
490  _states[dst_bucket] = State::FILLED;
491  new(_keys + dst_bucket) KeyT(std::move(src));
492  _num_filled += 1;
493 
494  src.~KeyT();
495  }
496  }
497 
498  // DCHECK_EQ_F(old_num_filled, _num_filled);
499 
500  free(old_states);
501  free(old_keys);
502  }
503 
504  protected:
505  // Find the bucket with this key, or return nullptr
506  template<typename T2>
507  size_t find_filled_bucket(const T2& key) const
508  {
509  if (empty()) { return (size_t)-1; } // Optimization
510 
511  auto hash_value = _hasher(key);
512  for (int offset=0; offset<=_max_probe_length; ++offset) {
513  auto bucket = (hash_value + offset) & _mask;
514  if (_states[bucket] == State::FILLED && agx::hashKeyEqual(_keys[bucket], key)) {
515  return bucket;
516  }
517  if (_states[bucket] == State::INACTIVE) {
518  return (size_t)-1; // End of the chain!
519  }
520  }
521  return (size_t)-1;
522  }
523 
524  void erase_bucket(size_t bucket) {
525  _states[bucket] = State::ACTIVE;
526  _keys[bucket].~KeyT();
527  _num_filled -= 1;
528  }
529 
530  private:
531  // Can we fit another element?
532  void check_expand_need()
533  {
534  reserve(_num_filled + 1);
535  }
536 
537  // Find the bucket with this key, or return a good empty bucket to place the key in.
538  // In the latter case, the bucket is expected to be filled.
539  size_t find_or_allocate(const KeyT& key)
540  {
541  auto hash_value = _hasher(key);
542  size_t hole = (size_t)-1;
543  int offset=0;
544  for (; offset<=_max_probe_length; ++offset) {
545  auto bucket = (hash_value + offset) & _mask;
546 
547  if (_states[bucket] == State::FILLED) {
548  if (agx::hashKeyEqual(_keys[bucket], key)) {
549  return bucket;
550  }
551  } else if (_states[bucket] == State::INACTIVE) {
552  return bucket;
553  } else {
554  // ACTIVE: keep searching
555  if (hole == (size_t)-1) {
556  hole = bucket;
557  }
558  }
559  }
560 
561  // No key found - but maybe a hole for it
562 
563  agxAssert(offset == _max_probe_length+1);
564 
565  if (hole != (size_t)-1) {
566  return hole;
567  }
568 
569  // No hole found within _max_probe_length
570  for (; ; ++offset) {
571  auto bucket = (hash_value + offset) & _mask;
572 
573  if (_states[bucket] != State::FILLED) {
574  _max_probe_length = offset;
575  return bucket;
576  }
577  }
578  }
579 
580  // key is not in this map. Find a place to put it.
581  size_t find_empty_bucket(const KeyT& key)
582  {
583  auto hash_value = _hasher(key);
584  for (int offset=0; ; ++offset) {
585  auto bucket = (hash_value + offset) & _mask;
586  if (_states[bucket] != State::FILLED) {
587  if (offset > _max_probe_length) {
588  _max_probe_length = offset;
589  }
590  return bucket;
591  }
592  }
593  }
594 
595  private:
596  HashT _hasher;
597  State* _states = nullptr;
598  KeyT* _keys = nullptr;
599  size_t _num_buckets = 0;
600  size_t _num_filled = 0;
601  int _max_probe_length = -1; // Our longest bucket-brigade is this long. ONLY when we have zero elements is this ever negative (-1).
602  size_t _mask = 0; // _num_buckets minus one
603  };
604 
605  template <typename KeyT, typename HashT>
607  {
608  return set.begin();
609  }
610 
611  template <typename KeyT, typename HashT>
613  {
614  return set.end();
615  }
616 
617 
618  template <typename KeyT, typename HashT>
620  {
621  return set.begin();
622  }
623 
624  template <typename KeyT, typename HashT>
626  {
627  return set.end();
628  }
629 
630 
638  template <typename KeyT, typename HashT = agx::HashFn<KeyT>>
640  {
641  public:
643 
645  {
646  }
647  };
648 
649 
650 
651  template <typename KeyT, typename HashT>
652  class LinearProbingHashSet< agx::ref_ptr<KeyT>, HashT> : public LinearProbingHashSetImplementation<agx::ref_ptr<KeyT>, HashT>
653  {
654  public:
656  typedef typename Implementation::iterator iterator;
657  typedef typename Implementation::const_iterator const_iterator;
658 
660  {}
661 
663  bool contains(const KeyT *key) const
664  {
665  return this->find_filled_bucket(key) != (size_t)-1;
666  }
667 
668  using Implementation::find;
669  iterator find(const KeyT *key)
670  {
671  auto bucket = this->find_filled_bucket(key);
672  if (bucket == (size_t)-1) {
673  return this->end();
674  }
675  return iterator(this, bucket);
676  }
677 
678  const_iterator find(const KeyT *key) const
679  {
680  auto bucket = this->find_filled_bucket(key);
681  if (bucket == (size_t)-1) {
682  return this->end();
683  }
684  return const_iterator(this, bucket);
685  }
686 
687  using Implementation::erase;
688  bool erase(const KeyT *key)
689  {
690  auto bucket = this->find_filled_bucket(key);
691  if (bucket != (size_t)-1) {
692  this->erase_bucket(bucket);
693  return true;
694  } else {
695  return false;
696  }
697  }
698 
699  };
700 }
const_iterator(const MyType *hash_set, size_t bucket)
insert_iterator(MyType *hash_set, size_t bucket, bool overwrite)
A cache-friendly hash set with open addressing, linear probing and power-of-two capacity.
size_t find_filled_bucket(const T2 &key) const
void swap(LinearProbingHashSetImplementation &other)
LinearProbingHashSetImplementation(LinearProbingHashSetImplementation &&other)
const_iterator find(const KeyT &key) const
LinearProbingHashSetImplementation & operator=(LinearProbingHashSetImplementation &&other)
insert_iterator insert(const KeyT &key)
void insert(const_iterator begin, const_iterator end)
LinearProbingHashSetImplementation(const LinearProbingHashSetImplementation &other)
LinearProbingHashSetImplementation & operator=(const LinearProbingHashSetImplementation &other)
insert_iterator emplace(Args &&... args)
LinearProbingHashSetImplementation< agx::ref_ptr< KeyT >, HashT > Implementation
Inheritance with partial specialization due to bug with ref_ptr containers.
LinearProbingHashSetImplementation< KeyT, HashT > Implementation
Smart pointer for handling referenced counted objects.
Definition: ref_ptr.h:30
#define agxAssert(expr)
Definition: debug.h:143
The agx namespace contains the dynamics/math part of the AGX Dynamics API.
LinearProbingHashSetImplementation< KeyT, HashT >::iterator begin(LinearProbingHashSetImplementation< KeyT, HashT > &set)
LinearProbingHashSetImplementation< KeyT, HashT >::iterator end(LinearProbingHashSetImplementation< KeyT, HashT > &set)
LinearProbingHashSetImplementation< KeyT, HashT >::const_iterator cend(const LinearProbingHashSetImplementation< KeyT, HashT > &set)
bool hashKeyEqual(const T1 &key1, const T2 &key2)
Definition: HashFunction.h:77
LinearProbingHashSetImplementation< KeyT, HashT >::const_iterator cbegin(const LinearProbingHashSetImplementation< KeyT, HashT > &set)