HashSet.h 17 KB

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