HashSet.h 14 KB

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