HashSet.h 16 KB

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