HashSet.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "HashBase.h"
  25. #include "Sort.h"
  26. #include <cassert>
  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 ++ () { GotoNext(); return *this; }
  68. /// Postincrement the pointer.
  69. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  70. /// Predecrement the pointer.
  71. Iterator& operator -- () { GotoPrev(); return *this; }
  72. /// Postdecrement the pointer.
  73. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  74. /// Point to the key.
  75. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  76. /// Dereference the key.
  77. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  78. };
  79. /// Hash set node const iterator.
  80. struct ConstIterator : public HashIteratorBase
  81. {
  82. /// Construct.
  83. ConstIterator()
  84. {
  85. }
  86. /// Construct with a node pointer.
  87. ConstIterator(Node* ptr) :
  88. HashIteratorBase(ptr)
  89. {
  90. }
  91. /// Construct from a non-const iterator.
  92. ConstIterator(const Iterator& rhs) :
  93. HashIteratorBase(rhs.ptr_)
  94. {
  95. }
  96. /// Assign from a non-const iterator.
  97. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  98. /// Preincrement the pointer.
  99. ConstIterator& operator ++ () { GotoNext(); return *this; }
  100. /// Postincrement the pointer.
  101. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  102. /// Predecrement the pointer.
  103. ConstIterator& operator -- () { GotoPrev(); return *this; }
  104. /// Postdecrement the pointer.
  105. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  106. /// Point to the key.
  107. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  108. /// Dereference the key.
  109. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  110. };
  111. /// Construct empty.
  112. HashSet()
  113. {
  114. // Reserve the tail node
  115. allocator_ = AllocatorInitialize(sizeof(Node));
  116. head_ = tail_ = ReserveNode();
  117. }
  118. /// Construct from another hash set.
  119. HashSet(const HashSet<T>& set)
  120. {
  121. // Reserve the tail node
  122. allocator_ = AllocatorInitialize(sizeof(Node));
  123. head_ = tail_ = ReserveNode();
  124. *this = set;
  125. }
  126. /// Destruct.
  127. ~HashSet()
  128. {
  129. Clear();
  130. FreeNode(Tail());
  131. AllocatorUninitialize(allocator_);
  132. }
  133. /// Assign a hash set.
  134. HashSet& operator = (const HashSet<T>& rhs)
  135. {
  136. Clear();
  137. Insert(rhs);
  138. return *this;
  139. }
  140. /// Add-assign a value.
  141. HashSet& operator += (const T& rhs)
  142. {
  143. Insert(rhs);
  144. return *this;
  145. }
  146. /// Add-assign a hash set.
  147. HashSet& operator += (const HashSet<T>& rhs)
  148. {
  149. Insert(rhs);
  150. return *this;
  151. }
  152. /// Test for equality with another hash set.
  153. bool operator == (const HashSet<T>& rhs) const
  154. {
  155. if (rhs.Size() != Size())
  156. return false;
  157. ConstIterator it = Begin();
  158. while (it != End())
  159. {
  160. if (!rhs.Contains(*it))
  161. return false;
  162. ++it;
  163. }
  164. return true;
  165. }
  166. /// Test for inequality with another hash set.
  167. bool operator != (const HashSet<T>& rhs) const
  168. {
  169. if (rhs.Size() != Size())
  170. return true;
  171. ConstIterator it = Begin();
  172. while (it != End())
  173. {
  174. if (!rhs.Contains(*it))
  175. return true;
  176. ++it;
  177. }
  178. return false;
  179. }
  180. /// Insert a key. Return an iterator to it.
  181. Iterator Insert(const T& key)
  182. {
  183. // If no pointers yet, allocate with minimum bucket count
  184. if (!ptrs_)
  185. {
  186. AllocateBuckets(Size(), MIN_BUCKETS);
  187. Rehash();
  188. }
  189. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  190. Node* existing = FindNode(key, hashKey);
  191. if (existing)
  192. return Iterator(existing);
  193. Node* newNode = InsertNode(Tail(), key);
  194. newNode->down_ = Ptrs()[hashKey];
  195. Ptrs()[hashKey] = newNode;
  196. // Rehash if the maximum load factor has been exceeded
  197. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  198. {
  199. AllocateBuckets(Size(), NumBuckets() << 1);
  200. Rehash();
  201. }
  202. return Iterator(newNode);
  203. }
  204. /// Insert a set.
  205. void Insert(const HashSet<T>& set)
  206. {
  207. ConstIterator it = set.Begin();
  208. ConstIterator end = set.End();
  209. while (it != end)
  210. Insert(*it++);
  211. }
  212. /// Insert a key by iterator. Return iterator to the value.
  213. Iterator Insert(const ConstIterator& it)
  214. {
  215. return Iterator(InsertNode(*it));
  216. }
  217. /// Erase a key. Return true if was found.
  218. bool Erase(const T& key)
  219. {
  220. if (!ptrs_)
  221. return false;
  222. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  223. Node* previous;
  224. Node* node = FindNode(key, hashKey, previous);
  225. if (!node)
  226. return false;
  227. if (previous)
  228. previous->down_ = node->down_;
  229. else
  230. Ptrs()[hashKey] = node->down_;
  231. EraseNode(node);
  232. return true;
  233. }
  234. /// Erase a key by iterator.
  235. Iterator Erase(const Iterator& it)
  236. {
  237. if (!ptrs_ || !it.ptr_)
  238. return End();
  239. Node* node = reinterpret_cast<Node*>(it.ptr_);
  240. Node* next = node->Next();
  241. unsigned hashKey = MakeHash(node->key_) & (NumBuckets() - 1);
  242. Node* previous = 0;
  243. Node* current = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  244. while (current && current != node)
  245. {
  246. previous = current;
  247. current = current->Down();
  248. }
  249. assert(current == node);
  250. if (previous)
  251. previous->down_ = node->down_;
  252. else
  253. Ptrs()[hashKey] = node->down_;
  254. EraseNode(node);
  255. return Iterator(next);
  256. }
  257. /// Clear the set.
  258. void Clear()
  259. {
  260. while (Size())
  261. EraseNode(Head());
  262. ResetPtrs();
  263. }
  264. /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
  265. void Sort()
  266. {
  267. unsigned numKeys = Size();
  268. if (!numKeys)
  269. return;
  270. Node** ptrs = new Node*[numKeys];
  271. Node* ptr = Head();
  272. for (unsigned i = 0; i < numKeys; ++i)
  273. {
  274. ptrs[i] = ptr;
  275. ptr = ptr->Next();
  276. }
  277. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  278. for (unsigned i = 0; i < numKeys; ++i)
  279. {
  280. ptrs[i]->next_ = (i < numKeys - 1) ? ptrs[i + 1] : tail_;
  281. ptrs[i]->prev_ = (i > 0) ? ptrs[i - 1] : 0;
  282. }
  283. head_ = ptrs[0];
  284. tail_->prev_ = ptrs[numKeys - 1];
  285. delete[] ptrs;
  286. }
  287. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  288. bool Rehash(unsigned numBuckets)
  289. {
  290. if (numBuckets == NumBuckets())
  291. return true;
  292. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  293. return false;
  294. // Check for being power of two
  295. unsigned check = numBuckets;
  296. while (!(check & 1))
  297. check >>= 1;
  298. if (check != 1)
  299. return false;
  300. AllocateBuckets(Size(), numBuckets);
  301. Rehash();
  302. return true;
  303. }
  304. /// Return iterator to the key, or end iterator if not found.
  305. Iterator Find(const T& key)
  306. {
  307. if (!ptrs_)
  308. return End();
  309. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  310. Node* node = FindNode(key, hashKey);
  311. if (node)
  312. return Iterator(node);
  313. else
  314. return End();
  315. }
  316. /// Return const iterator to the key, or end iterator if not found.
  317. ConstIterator Find(const T& key) const
  318. {
  319. if (!ptrs_)
  320. return End();
  321. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  322. Node* node = FindNode(key, hashKey);
  323. if (node)
  324. return ConstIterator(node);
  325. else
  326. return End();
  327. }
  328. /// Return whether contains a key.
  329. bool Contains(const T& key) const
  330. {
  331. if (!ptrs_)
  332. return false;
  333. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  334. return FindNode(key, hashKey) != 0;
  335. }
  336. /// Return iterator to the beginning.
  337. Iterator Begin() { return Iterator(Head()); }
  338. /// Return iterator to the beginning.
  339. ConstIterator Begin() const { return ConstIterator(Head()); }
  340. /// Return iterator to the end.
  341. Iterator End() { return Iterator(Tail()); }
  342. /// Return iterator to the end.
  343. ConstIterator End() const { return ConstIterator(Tail()); }
  344. /// Return first key.
  345. const T& Front() const { return *Begin(); }
  346. /// Return last key.
  347. const T& Back() const { return *(--End()); }
  348. private:
  349. /// Return the head node.
  350. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  351. /// Return the tail node.
  352. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  353. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  354. Node* FindNode(const T& key, unsigned hashKey) const
  355. {
  356. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  357. while (node)
  358. {
  359. if (node->key_ == key)
  360. return node;
  361. node = node->Down();
  362. }
  363. return 0;
  364. }
  365. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  366. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  367. {
  368. previous = 0;
  369. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  370. while (node)
  371. {
  372. if (node->key_ == key)
  373. return node;
  374. previous = node;
  375. node = node->Down();
  376. }
  377. return 0;
  378. }
  379. /// Insert a node into the list. Return the new node.
  380. Node* InsertNode(Node* dest, const T& key)
  381. {
  382. if (!dest)
  383. return 0;
  384. Node* newNode = ReserveNode(key);
  385. Node* prev = dest->Prev();
  386. newNode->next_ = dest;
  387. newNode->prev_ = prev;
  388. if (prev)
  389. prev->next_ = newNode;
  390. dest->prev_ = newNode;
  391. // Reassign the head node if necessary
  392. if (dest == Head())
  393. head_ = newNode;
  394. SetSize(Size() + 1);
  395. return newNode;
  396. }
  397. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  398. Node* EraseNode(Node* node)
  399. {
  400. // The tail node can not be removed
  401. if (!node || node == tail_)
  402. return Tail();
  403. Node* prev = node->Prev();
  404. Node* next = node->Next();
  405. if (prev)
  406. prev->next_ = next;
  407. next->prev_ = prev;
  408. // Reassign the head node if necessary
  409. if (node == Head())
  410. head_ = next;
  411. FreeNode(node);
  412. SetSize(Size() - 1);
  413. return next;
  414. }
  415. /// Reserve a node.
  416. Node* ReserveNode()
  417. {
  418. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  419. new(newNode) Node();
  420. return newNode;
  421. }
  422. /// Reserve a node with specified key.
  423. Node* ReserveNode(const T& key)
  424. {
  425. if (!allocator_)
  426. allocator_ = AllocatorInitialize(sizeof(Node));
  427. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  428. new(newNode) Node(key);
  429. return newNode;
  430. }
  431. /// Free a node.
  432. void FreeNode(Node* node)
  433. {
  434. (node)->~Node();
  435. AllocatorFree(allocator_, node);
  436. }
  437. /// Rehash the buckets.
  438. void Rehash()
  439. {
  440. for (Iterator it = Begin(); it != End(); ++it)
  441. {
  442. Node* node = reinterpret_cast<Node*>(it.ptr_);
  443. unsigned hashKey = MakeHash(*it) & (NumBuckets() - 1);
  444. node->down_ = Ptrs()[hashKey];
  445. Ptrs()[hashKey] = node;
  446. }
  447. }
  448. /// Compare two nodes.
  449. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
  450. };
  451. }