HashSet.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  1. //
  2. // Copyright (c) 2008-2020 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashBase.h"
  24. #include "../Container/Sort.h"
  25. #include <cassert>
  26. #include <initializer_list>
  27. namespace Urho3D
  28. {
  29. /// Hash set template class.
  30. template <class T> class HashSet : public HashBase
  31. {
  32. public:
  33. /// Hash set node.
  34. struct Node : public HashNodeBase
  35. {
  36. /// Construct undefined.
  37. Node() = default;
  38. /// Construct with key.
  39. explicit Node(const T& key) :
  40. key_(key)
  41. {
  42. }
  43. /// Key.
  44. T key_;
  45. /// Return next node.
  46. Node* Next() const { return static_cast<Node*>(next_); }
  47. /// Return previous node.
  48. Node* Prev() const { return static_cast<Node*>(prev_); }
  49. /// Return next node in the bucket.
  50. Node* Down() const { return static_cast<Node*>(down_); }
  51. };
  52. /// Hash set node iterator.
  53. struct Iterator : public HashIteratorBase
  54. {
  55. /// Construct.
  56. Iterator() = default;
  57. /// Construct with a node pointer.
  58. explicit Iterator(Node* ptr) :
  59. HashIteratorBase(ptr)
  60. {
  61. }
  62. /// Preincrement the pointer.
  63. Iterator& operator ++()
  64. {
  65. GotoNext();
  66. return *this;
  67. }
  68. /// Postincrement the pointer.
  69. Iterator operator ++(int)
  70. {
  71. Iterator it = *this;
  72. GotoNext();
  73. return it;
  74. }
  75. /// Predecrement the pointer.
  76. Iterator& operator --()
  77. {
  78. GotoPrev();
  79. return *this;
  80. }
  81. /// Postdecrement the pointer.
  82. Iterator operator --(int)
  83. {
  84. Iterator it = *this;
  85. GotoPrev();
  86. return it;
  87. }
  88. /// Point to the key.
  89. const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
  90. /// Dereference the key.
  91. const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
  92. };
  93. /// Hash set node const iterator.
  94. struct ConstIterator : public HashIteratorBase
  95. {
  96. /// Construct.
  97. ConstIterator() = default;
  98. /// Construct with a node pointer.
  99. explicit ConstIterator(Node* ptr) :
  100. HashIteratorBase(ptr)
  101. {
  102. }
  103. /// Construct from a non-const iterator.
  104. ConstIterator(const Iterator& rhs) : // NOLINT(google-explicit-constructor)
  105. HashIteratorBase(rhs.ptr_)
  106. {
  107. }
  108. /// Assign from a non-const iterator.
  109. ConstIterator& operator =(const Iterator& rhs)
  110. {
  111. ptr_ = rhs.ptr_;
  112. return *this;
  113. }
  114. /// Preincrement the pointer.
  115. ConstIterator& operator ++()
  116. {
  117. GotoNext();
  118. return *this;
  119. }
  120. /// Postincrement the pointer.
  121. ConstIterator operator ++(int)
  122. {
  123. ConstIterator it = *this;
  124. GotoNext();
  125. return it;
  126. }
  127. /// Predecrement the pointer.
  128. ConstIterator& operator --()
  129. {
  130. GotoPrev();
  131. return *this;
  132. }
  133. /// Postdecrement the pointer.
  134. ConstIterator operator --(int)
  135. {
  136. ConstIterator it = *this;
  137. GotoPrev();
  138. return it;
  139. }
  140. /// Point to the key.
  141. const T* operator ->() const { return &(static_cast<Node*>(ptr_))->key_; }
  142. /// Dereference the key.
  143. const T& operator *() const { return (static_cast<Node*>(ptr_))->key_; }
  144. };
  145. /// Construct empty.
  146. HashSet()
  147. {
  148. // Reserve the tail node
  149. allocator_ = AllocatorInitialize((unsigned)sizeof(Node));
  150. head_ = tail_ = ReserveNode();
  151. }
  152. /// Construct from another hash set.
  153. HashSet(const HashSet<T>& set)
  154. {
  155. // Reserve the tail node + initial capacity according to the set's size
  156. allocator_ = AllocatorInitialize((unsigned)sizeof(Node), set.Size() + 1);
  157. head_ = tail_ = ReserveNode();
  158. *this = set;
  159. }
  160. /// Move-construct from another hash set.
  161. HashSet(HashSet<T> && set) noexcept
  162. {
  163. Swap(set);
  164. }
  165. /// Aggregate initialization constructor.
  166. HashSet(const std::initializer_list<T>& list) : HashSet()
  167. {
  168. for (auto it = list.begin(); it != list.end(); it++)
  169. {
  170. Insert(*it);
  171. }
  172. }
  173. /// Destruct.
  174. ~HashSet()
  175. {
  176. if (allocator_)
  177. {
  178. Clear();
  179. FreeNode(Tail());
  180. AllocatorUninitialize(allocator_);
  181. delete[] ptrs_;
  182. }
  183. }
  184. /// Assign a hash set.
  185. HashSet& operator =(const HashSet<T>& rhs)
  186. {
  187. // In case of self-assignment do nothing
  188. if (&rhs != this)
  189. {
  190. Clear();
  191. Insert(rhs);
  192. }
  193. return *this;
  194. }
  195. /// Move-assign a hash set.
  196. HashSet& operator =(HashSet<T> && rhs) noexcept
  197. {
  198. Swap(rhs);
  199. return *this;
  200. }
  201. /// Add-assign a value.
  202. HashSet& operator +=(const T& rhs)
  203. {
  204. Insert(rhs);
  205. return *this;
  206. }
  207. /// Add-assign a hash set.
  208. HashSet& operator +=(const HashSet<T>& rhs)
  209. {
  210. Insert(rhs);
  211. return *this;
  212. }
  213. /// Test for equality with another hash set.
  214. bool operator ==(const HashSet<T>& rhs) const
  215. {
  216. if (rhs.Size() != Size())
  217. return false;
  218. ConstIterator it = Begin();
  219. while (it != End())
  220. {
  221. if (!rhs.Contains(*it))
  222. return false;
  223. ++it;
  224. }
  225. return true;
  226. }
  227. /// Test for inequality with another hash set.
  228. bool operator !=(const HashSet<T>& rhs) const
  229. {
  230. if (rhs.Size() != Size())
  231. return true;
  232. ConstIterator it = Begin();
  233. while (it != End())
  234. {
  235. if (!rhs.Contains(*it))
  236. return true;
  237. ++it;
  238. }
  239. return false;
  240. }
  241. /// Insert a key. Return an iterator to it.
  242. Iterator Insert(const T& key)
  243. {
  244. // If no pointers yet, allocate with minimum bucket count
  245. if (!ptrs_)
  246. {
  247. AllocateBuckets(Size(), MIN_BUCKETS);
  248. Rehash();
  249. }
  250. unsigned hashKey = Hash(key);
  251. Node* existing = FindNode(key, hashKey);
  252. if (existing)
  253. return Iterator(existing);
  254. Node* newNode = InsertNode(Tail(), key);
  255. newNode->down_ = Ptrs()[hashKey];
  256. Ptrs()[hashKey] = newNode;
  257. // Rehash if the maximum load factor has been exceeded
  258. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  259. {
  260. AllocateBuckets(Size(), NumBuckets() << 1);
  261. Rehash();
  262. }
  263. return Iterator(newNode);
  264. }
  265. /// Insert a key. Return an iterator and set exists flag according to whether the key already existed.
  266. Iterator Insert(const T& key, bool& exists)
  267. {
  268. unsigned oldSize = Size();
  269. Iterator ret = Insert(key);
  270. exists = (Size() == oldSize);
  271. return ret;
  272. }
  273. /// Insert a set.
  274. void Insert(const HashSet<T>& set)
  275. {
  276. ConstIterator it = set.Begin();
  277. ConstIterator end = set.End();
  278. while (it != end)
  279. Insert(*it++);
  280. }
  281. /// Insert a key by iterator. Return iterator to the value.
  282. Iterator Insert(const ConstIterator& it)
  283. {
  284. return Iterator(InsertNode(*it));
  285. }
  286. /// Erase a key. Return true if was found.
  287. bool Erase(const T& key)
  288. {
  289. if (!ptrs_)
  290. return false;
  291. unsigned hashKey = Hash(key);
  292. Node* previous;
  293. Node* node = FindNode(key, hashKey, previous);
  294. if (!node)
  295. return false;
  296. if (previous)
  297. previous->down_ = node->down_;
  298. else
  299. Ptrs()[hashKey] = node->down_;
  300. EraseNode(node);
  301. return true;
  302. }
  303. /// Erase a key by iterator. Return iterator to the next key.
  304. Iterator Erase(const Iterator& it)
  305. {
  306. if (!ptrs_ || !it.ptr_)
  307. return End();
  308. auto* node = static_cast<Node*>(it.ptr_);
  309. Node* next = node->Next();
  310. unsigned hashKey = Hash(node->key_);
  311. Node* previous = 0;
  312. auto* current = static_cast<Node*>(Ptrs()[hashKey]);
  313. while (current && current != node)
  314. {
  315. previous = current;
  316. current = current->Down();
  317. }
  318. assert(current == node);
  319. if (previous)
  320. previous->down_ = node->down_;
  321. else
  322. Ptrs()[hashKey] = node->down_;
  323. EraseNode(node);
  324. return Iterator(next);
  325. }
  326. /// Clear the set.
  327. void Clear()
  328. {
  329. // Prevent Find() from returning anything while the map is being cleared
  330. ResetPtrs();
  331. if (Size())
  332. {
  333. for (Iterator i = Begin(); i != End();)
  334. {
  335. FreeNode(static_cast<Node*>(i++.ptr_));
  336. i.ptr_->prev_ = 0;
  337. }
  338. head_ = tail_;
  339. SetSize(0);
  340. }
  341. }
  342. /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
  343. void Sort()
  344. {
  345. unsigned numKeys = Size();
  346. if (!numKeys)
  347. return;
  348. auto** ptrs = new Node* [numKeys];
  349. Node* ptr = Head();
  350. for (unsigned i = 0; i < numKeys; ++i)
  351. {
  352. ptrs[i] = ptr;
  353. ptr = ptr->Next();
  354. }
  355. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  356. head_ = ptrs[0];
  357. ptrs[0]->prev_ = 0;
  358. for (unsigned i = 1; i < numKeys; ++i)
  359. {
  360. ptrs[i - 1]->next_ = ptrs[i];
  361. ptrs[i]->prev_ = ptrs[i - 1];
  362. }
  363. ptrs[numKeys - 1]->next_ = tail_;
  364. tail_->prev_ = ptrs[numKeys - 1];
  365. delete[] ptrs;
  366. }
  367. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  368. bool Rehash(unsigned numBuckets)
  369. {
  370. if (numBuckets == NumBuckets())
  371. return true;
  372. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  373. return false;
  374. // Check for being power of two
  375. unsigned check = numBuckets;
  376. while (!(check & 1u))
  377. check >>= 1;
  378. if (check != 1)
  379. return false;
  380. AllocateBuckets(Size(), numBuckets);
  381. Rehash();
  382. return true;
  383. }
  384. /// Return iterator to the key, or end iterator if not found.
  385. Iterator Find(const T& key)
  386. {
  387. if (!ptrs_)
  388. return End();
  389. unsigned hashKey = Hash(key);
  390. Node* node = FindNode(key, hashKey);
  391. if (node)
  392. return Iterator(node);
  393. else
  394. return End();
  395. }
  396. /// Return const iterator to the key, or end iterator if not found.
  397. ConstIterator Find(const T& key) const
  398. {
  399. if (!ptrs_)
  400. return End();
  401. unsigned hashKey = Hash(key);
  402. Node* node = FindNode(key, hashKey);
  403. if (node)
  404. return ConstIterator(node);
  405. else
  406. return End();
  407. }
  408. /// Return whether contains a key.
  409. bool Contains(const T& key) const
  410. {
  411. if (!ptrs_)
  412. return false;
  413. unsigned hashKey = Hash(key);
  414. return FindNode(key, hashKey) != 0;
  415. }
  416. /// Return iterator to the beginning.
  417. Iterator Begin() { return Iterator(Head()); }
  418. /// Return iterator to the beginning.
  419. ConstIterator Begin() const { return ConstIterator(Head()); }
  420. /// Return iterator to the end.
  421. Iterator End() { return Iterator(Tail()); }
  422. /// Return iterator to the end.
  423. ConstIterator End() const { return ConstIterator(Tail()); }
  424. /// Return first key.
  425. const T& Front() const { return *Begin(); }
  426. /// Return last key.
  427. const T& Back() const { return *(--End()); }
  428. private:
  429. /// Return the head node.
  430. Node* Head() const { return static_cast<Node*>(head_); }
  431. /// Return the tail node.
  432. Node* Tail() const { return static_cast<Node*>(tail_); }
  433. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  434. Node* FindNode(const T& key, unsigned hashKey) const
  435. {
  436. auto* node = static_cast<Node*>(Ptrs()[hashKey]);
  437. while (node)
  438. {
  439. if (node->key_ == key)
  440. return node;
  441. node = node->Down();
  442. }
  443. return 0;
  444. }
  445. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  446. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  447. {
  448. previous = 0;
  449. auto* node = static_cast<Node*>(Ptrs()[hashKey]);
  450. while (node)
  451. {
  452. if (node->key_ == key)
  453. return node;
  454. previous = node;
  455. node = node->Down();
  456. }
  457. return 0;
  458. }
  459. /// Insert a node into the list. Return the new node.
  460. Node* InsertNode(Node* dest, const T& key)
  461. {
  462. if (!dest)
  463. return 0;
  464. Node* newNode = ReserveNode(key);
  465. Node* prev = dest->Prev();
  466. newNode->next_ = dest;
  467. newNode->prev_ = prev;
  468. if (prev)
  469. prev->next_ = newNode;
  470. dest->prev_ = newNode;
  471. // Reassign the head node if necessary
  472. if (dest == Head())
  473. head_ = newNode;
  474. SetSize(Size() + 1);
  475. return newNode;
  476. }
  477. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  478. Node* EraseNode(Node* node)
  479. {
  480. // The tail node can not be removed
  481. if (!node || node == tail_)
  482. return Tail();
  483. Node* prev = node->Prev();
  484. Node* next = node->Next();
  485. if (prev)
  486. prev->next_ = next;
  487. next->prev_ = prev;
  488. // Reassign the head node if necessary
  489. if (node == Head())
  490. head_ = next;
  491. FreeNode(node);
  492. SetSize(Size() - 1);
  493. return next;
  494. }
  495. /// Reserve a node.
  496. Node* ReserveNode()
  497. {
  498. auto* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  499. new(newNode) Node();
  500. return newNode;
  501. }
  502. /// Reserve a node with specified key.
  503. Node* ReserveNode(const T& key)
  504. {
  505. auto* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  506. new(newNode) Node(key);
  507. return newNode;
  508. }
  509. /// Free a node.
  510. void FreeNode(Node* node)
  511. {
  512. (node)->~Node();
  513. AllocatorFree(allocator_, node);
  514. }
  515. /// Rehash the buckets.
  516. void Rehash()
  517. {
  518. for (Iterator it = Begin(); it != End(); ++it)
  519. {
  520. auto* node = static_cast<Node*>(it.ptr_);
  521. unsigned hashKey = Hash(*it);
  522. node->down_ = Ptrs()[hashKey];
  523. Ptrs()[hashKey] = node;
  524. }
  525. }
  526. /// Compare two nodes.
  527. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
  528. /// Compute a hash based on the key and the bucket size.
  529. unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
  530. };
  531. template <class T> typename Urho3D::HashSet<T>::ConstIterator begin(const Urho3D::HashSet<T>& v) { return v.Begin(); }
  532. template <class T> typename Urho3D::HashSet<T>::ConstIterator end(const Urho3D::HashSet<T>& v) { return v.End(); }
  533. template <class T> typename Urho3D::HashSet<T>::Iterator begin(Urho3D::HashSet<T>& v) { return v.Begin(); }
  534. template <class T> typename Urho3D::HashSet<T>::Iterator end(Urho3D::HashSet<T>& v) { return v.End(); }
  535. }