HashSet.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Öörni
  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. /// Hash set template class.
  26. template <class T> class HashSet : public HashBase
  27. {
  28. public:
  29. /// Hash set node.
  30. struct Node : public HashNodeBase
  31. {
  32. /// Construct undefined.
  33. Node()
  34. {
  35. }
  36. /// Construct with key.
  37. Node(const T& key) :
  38. key_(key)
  39. {
  40. }
  41. /// Key.
  42. T key_;
  43. /// Return next node.
  44. Node* Next() const { return static_cast<Node*>(next_); }
  45. /// Return previous node.
  46. Node* Prev() const { return static_cast<Node*>(prev_); }
  47. /// Return next node in the bucket.
  48. Node* Down() const { return static_cast<Node*>(down_); }
  49. };
  50. /// Hash set node iterator.
  51. struct Iterator : public HashIteratorBase
  52. {
  53. /// Construct.
  54. Iterator()
  55. {
  56. }
  57. /// Construct with a node pointer.
  58. Iterator(Node* ptr) :
  59. HashIteratorBase(ptr)
  60. {
  61. }
  62. /// Preincrement the pointer.
  63. Iterator& operator ++ () { GotoNext(); return *this; }
  64. /// Postincrement the pointer.
  65. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  66. /// Predecrement the pointer.
  67. Iterator& operator -- () { GotoPrev(); return *this; }
  68. /// Postdecrement the pointer.
  69. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  70. /// Point to the key.
  71. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  72. /// Dereference the key.
  73. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  74. };
  75. /// Hash set node const iterator.
  76. struct ConstIterator : public HashIteratorBase
  77. {
  78. /// Construct.
  79. ConstIterator()
  80. {
  81. }
  82. /// Construct with a node pointer.
  83. ConstIterator(Node* ptr) :
  84. HashIteratorBase(ptr)
  85. {
  86. }
  87. /// Construct from a non-const iterator.
  88. ConstIterator(const Iterator& rhs) :
  89. HashIteratorBase(rhs.ptr_)
  90. {
  91. }
  92. /// Assign from a non-const iterator.
  93. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  94. /// Preincrement the pointer.
  95. ConstIterator& operator ++ () { GotoNext(); return *this; }
  96. /// Postincrement the pointer.
  97. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  98. /// Predecrement the pointer.
  99. ConstIterator& operator -- () { GotoPrev(); return *this; }
  100. /// Postdecrement the pointer.
  101. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  102. /// Point to the key.
  103. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  104. /// Dereference the key.
  105. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  106. };
  107. /// Construct empty.
  108. HashSet()
  109. {
  110. // Reserve the tail node
  111. allocator_ = AllocatorInitialize(sizeof(Node));
  112. head_ = tail_ = ReserveNode();
  113. }
  114. /// Construct from another hash set.
  115. HashSet(const HashSet<T>& set)
  116. {
  117. // Reserve the tail node
  118. allocator_ = AllocatorInitialize(sizeof(Node));
  119. head_ = tail_ = ReserveNode();
  120. *this = set;
  121. }
  122. /// Destruct.
  123. ~HashSet()
  124. {
  125. Clear();
  126. FreeNode(Tail());
  127. AllocatorUninitialize(allocator_);
  128. }
  129. /// Assign a hash set.
  130. HashSet& operator = (const HashSet<T>& rhs)
  131. {
  132. Clear();
  133. Insert(rhs);
  134. return *this;
  135. }
  136. /// Add-assign a value.
  137. HashSet& operator += (const T& rhs)
  138. {
  139. Insert(rhs);
  140. return *this;
  141. }
  142. /// Add-assign a hash set.
  143. HashSet& operator += (const HashSet<T>& rhs)
  144. {
  145. Insert(rhs);
  146. return *this;
  147. }
  148. /// Test for equality with another hash set.
  149. bool operator == (const HashSet<T>& rhs) const
  150. {
  151. if (rhs.Size() != Size())
  152. return false;
  153. ConstIterator it = Begin();
  154. while (it != End())
  155. {
  156. if (!rhs.Contains(*it))
  157. return false;
  158. ++it;
  159. }
  160. return true;
  161. }
  162. /// Test for inequality with another hash set.
  163. bool operator != (const HashSet<T>& rhs) const
  164. {
  165. if (rhs.Size() != Size())
  166. return true;
  167. ConstIterator it = Begin();
  168. while (it != End())
  169. {
  170. if (!rhs.Contains(*it))
  171. return true;
  172. ++it;
  173. }
  174. return false;
  175. }
  176. /// Insert a key. Return an iterator to it.
  177. Iterator Insert(const T& key)
  178. {
  179. // If no pointers yet, allocate with minimum bucket count
  180. if (!ptrs_)
  181. {
  182. AllocateBuckets(Size(), MIN_BUCKETS);
  183. Rehash();
  184. }
  185. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  186. Node* existing = FindNode(key, hashKey);
  187. if (existing)
  188. return Iterator(existing);
  189. Node* newNode = InsertNode(Tail(), key);
  190. newNode->down_ = Ptrs()[hashKey];
  191. Ptrs()[hashKey] = newNode;
  192. // Rehash if the maximum load factor has been exceeded
  193. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  194. {
  195. AllocateBuckets(Size(), NumBuckets() << 1);
  196. Rehash();
  197. }
  198. return Iterator(newNode);
  199. }
  200. /// Insert a set.
  201. void Insert(const HashSet<T>& set)
  202. {
  203. ConstIterator it = set.Begin();
  204. ConstIterator end = set.End();
  205. while (it != end)
  206. Insert(*it++);
  207. }
  208. /// Insert a key by iterator. Return iterator to the value.
  209. Iterator Insert(const ConstIterator& it)
  210. {
  211. return Iterator(InsertNode(*it));
  212. }
  213. /// Erase a key. Return true if was found.
  214. bool Erase(const T& key)
  215. {
  216. if (!ptrs_)
  217. return false;
  218. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  219. Node* previous;
  220. Node* node = FindNode(key, hashKey, previous);
  221. if (!node)
  222. return false;
  223. if (previous)
  224. previous->down_ = node->down_;
  225. else
  226. Ptrs()[hashKey] = node->down_;
  227. EraseNode(node);
  228. return true;
  229. }
  230. /// Erase a key by iterator.
  231. void Erase(const Iterator& it) { Erase(*it); }
  232. /// Clear the set.
  233. void Clear()
  234. {
  235. while (Size())
  236. EraseNode(Head());
  237. ResetPtrs();
  238. }
  239. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  240. bool Rehash(unsigned numBuckets)
  241. {
  242. if (numBuckets == NumBuckets())
  243. return true;
  244. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  245. return false;
  246. // Check for being power of two
  247. unsigned check = numBuckets;
  248. while (!(check & 1))
  249. check >>= 1;
  250. if (check != 1)
  251. return false;
  252. AllocateBuckets(Size(), numBuckets);
  253. Rehash();
  254. return true;
  255. }
  256. /// Return iterator to the key, or end iterator if not found.
  257. Iterator Find(const T& key)
  258. {
  259. if (!ptrs_)
  260. return End();
  261. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  262. Node* node = FindNode(key, hashKey);
  263. if (node)
  264. return Iterator(node);
  265. else
  266. return End();
  267. }
  268. /// Return const iterator to the key, or end iterator if not found.
  269. ConstIterator Find(const T& key) const
  270. {
  271. if (!ptrs_)
  272. return End();
  273. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  274. Node* node = FindNode(key, hashKey);
  275. if (node)
  276. return ConstIterator(node);
  277. else
  278. return End();
  279. }
  280. /// Return whether contains a key.
  281. bool Contains(const T& key) const
  282. {
  283. if (!ptrs_)
  284. return false;
  285. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  286. return FindNode(key, hashKey) != 0;
  287. }
  288. /// Return iterator to the beginning.
  289. Iterator Begin() { return Iterator(Head()); }
  290. /// Return iterator to the beginning.
  291. ConstIterator Begin() const { return ConstIterator(Head()); }
  292. /// Return iterator to the end.
  293. Iterator End() { return Iterator(Tail()); }
  294. /// Return iterator to the end.
  295. ConstIterator End() const { return ConstIterator(Tail()); }
  296. /// Return first key.
  297. const T& Front() const { return *Begin(); }
  298. /// Return last key.
  299. const T& Back() const { return *(--End()); }
  300. private:
  301. /// Return the head node.
  302. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  303. /// Return the tail node.
  304. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  305. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  306. Node* FindNode(const T& key, unsigned hashKey) const
  307. {
  308. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  309. while (node)
  310. {
  311. if (node->key_ == key)
  312. return node;
  313. node = node->Down();
  314. }
  315. return 0;
  316. }
  317. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  318. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  319. {
  320. previous = 0;
  321. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  322. while (node)
  323. {
  324. if (node->key_ == key)
  325. return node;
  326. previous = node;
  327. node = node->Down();
  328. }
  329. return 0;
  330. }
  331. /// Insert a node into the list. Return the new node.
  332. Node* InsertNode(Node* dest, const T& key)
  333. {
  334. if (!dest)
  335. return 0;
  336. Node* newNode = ReserveNode(key);
  337. Node* prev = dest->Prev();
  338. newNode->next_ = dest;
  339. newNode->prev_ = prev;
  340. if (prev)
  341. prev->next_ = newNode;
  342. dest->prev_ = newNode;
  343. // Reassign the head node if necessary
  344. if (dest == Head())
  345. head_ = newNode;
  346. SetSize(Size() + 1);
  347. return newNode;
  348. }
  349. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  350. Node* EraseNode(Node* node)
  351. {
  352. // The tail node can not be removed
  353. if (!node || node == tail_)
  354. return Tail();
  355. Node* prev = node->Prev();
  356. Node* next = node->Next();
  357. if (prev)
  358. prev->next_ = next;
  359. next->prev_ = prev;
  360. // Reassign the head node if necessary
  361. if (node == Head())
  362. head_ = next;
  363. FreeNode(node);
  364. SetSize(Size() - 1);
  365. return next;
  366. }
  367. /// Reserve a node.
  368. Node* ReserveNode()
  369. {
  370. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  371. new(newNode) Node();
  372. return newNode;
  373. }
  374. /// Reserve a node with specified key.
  375. Node* ReserveNode(const T& key)
  376. {
  377. if (!allocator_)
  378. allocator_ = AllocatorInitialize(sizeof(Node));
  379. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  380. new(newNode) Node(key);
  381. return newNode;
  382. }
  383. /// Free a node.
  384. void FreeNode(Node* node)
  385. {
  386. (node)->~Node();
  387. AllocatorFree(allocator_, node);
  388. }
  389. /// Rehash the buckets.
  390. void Rehash()
  391. {
  392. for (Iterator it = Begin(); it != End(); ++it)
  393. {
  394. Node* node = reinterpret_cast<Node*>(it.ptr_);
  395. unsigned hashKey = MakeHash(*it) & (NumBuckets() - 1);
  396. node->down_ = Ptrs()[hashKey];
  397. Ptrs()[hashKey] = node;
  398. }
  399. }
  400. };