HashSet.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  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. delete[] ptrs_;
  129. }
  130. /// Assign a hash set.
  131. HashSet& operator = (const HashSet<T>& rhs)
  132. {
  133. Clear();
  134. Insert(rhs);
  135. return *this;
  136. }
  137. /// Add-assign a value.
  138. HashSet& operator += (const T& rhs)
  139. {
  140. Insert(rhs);
  141. return *this;
  142. }
  143. /// Add-assign a hash set.
  144. HashSet& operator += (const HashSet<T>& rhs)
  145. {
  146. Insert(rhs);
  147. return *this;
  148. }
  149. /// Test for equality with another hash set. Warning: this is much slower than checking equality of two sets.
  150. bool operator == (const HashSet<T>& rhs) const
  151. {
  152. if (rhs.size_ != size_)
  153. return false;
  154. ConstIterator it = Begin();
  155. while (it != End())
  156. {
  157. if (!rhs.Contains(*it))
  158. return false;
  159. ++it;
  160. }
  161. return true;
  162. }
  163. /// Test for inequality with another hash set. Warning: this is much slower than checking inequality of two sets.
  164. bool operator != (const HashSet<T>& rhs) const
  165. {
  166. if (rhs.size_ != size_)
  167. return true;
  168. ConstIterator it = Begin();
  169. while (it != End())
  170. {
  171. if (!rhs.Contains(*it))
  172. return true;
  173. ++it;
  174. }
  175. return false;
  176. }
  177. /// Insert a key. Return an iterator to it.
  178. Iterator Insert(const T& key)
  179. {
  180. // If no pointers yet, allocate with minimum bucket count
  181. if (!ptrs_)
  182. {
  183. numBuckets_ = MIN_BUCKETS;
  184. Rehash();
  185. }
  186. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  187. Node* existing = FindNode(key, hashKey);
  188. if (existing)
  189. return Iterator(existing);
  190. Node* newNode = InsertNode(Tail(), key);
  191. newNode->down_ = ptrs_[hashKey];
  192. ptrs_[hashKey] = newNode;
  193. // Rehash if the maximum load factor has been exceeded
  194. if (size_ > numBuckets_ * MAX_LOAD_FACTOR)
  195. {
  196. numBuckets_ <<= 1;
  197. Rehash();
  198. }
  199. return Iterator(newNode);
  200. }
  201. /// Insert a set.
  202. void Insert(const HashSet<T>& set)
  203. {
  204. ConstIterator it = set.Begin();
  205. ConstIterator end = set.End();
  206. while (it != end)
  207. Insert(*it++);
  208. }
  209. /// Insert a key by iterator. Return iterator to the value.
  210. Iterator Insert(const ConstIterator& it)
  211. {
  212. return Iterator(InsertNode(*it));
  213. }
  214. /// Erase a key. Return true if was found.
  215. bool Erase(const T& key)
  216. {
  217. if (!numBuckets_)
  218. return false;
  219. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  220. Node* previous;
  221. Node* node = FindNode(key, hashKey, previous);
  222. if (!node)
  223. return false;
  224. if (previous)
  225. previous->down_ = node->down_;
  226. else
  227. ptrs_[hashKey] = node->down_;
  228. EraseNode(node);
  229. return true;
  230. }
  231. /// Erase a key by iterator.
  232. void Erase(const Iterator& it) { Erase(*it); }
  233. /// Clear the set.
  234. void Clear()
  235. {
  236. while (size_)
  237. EraseNode(Head());
  238. // Reset bucket pointers
  239. for (unsigned i = 0; i < numBuckets_; ++i)
  240. ptrs_[i] = 0;
  241. }
  242. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  243. bool Rehash(unsigned numBuckets)
  244. {
  245. if (numBuckets == numBuckets_)
  246. return true;
  247. if (!numBuckets || numBuckets < size_ / MAX_LOAD_FACTOR)
  248. return false;
  249. // Check for being power of two
  250. unsigned check = numBuckets;
  251. while (!(check & 1))
  252. check >>= 1;
  253. if (check != 1)
  254. return false;
  255. numBuckets_ = numBuckets;
  256. Rehash();
  257. return true;
  258. }
  259. /// Return iterator to the key, or end iterator if not found.
  260. Iterator Find(const T& key)
  261. {
  262. if (!numBuckets_)
  263. return End();
  264. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  265. Node* node = FindNode(key, hashKey);
  266. if (node)
  267. return Iterator(node);
  268. else
  269. return End();
  270. }
  271. /// Return const iterator to the key, or end iterator if not found.
  272. ConstIterator Find(const T& key) const
  273. {
  274. if (!numBuckets_)
  275. return End();
  276. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  277. Node* node = FindNode(key, hashKey);
  278. if (node)
  279. return ConstIterator(node);
  280. else
  281. return End();
  282. }
  283. /// Return whether contains a key.
  284. bool Contains(const T& key) const
  285. {
  286. if (!numBuckets_)
  287. return false;
  288. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  289. return FindNode(key, hashKey) != 0;
  290. }
  291. /// Return iterator to the beginning.
  292. Iterator Begin() { return Iterator(Head()); }
  293. /// Return iterator to the beginning.
  294. ConstIterator Begin() const { return ConstIterator(Head()); }
  295. /// Return iterator to the end.
  296. Iterator End() { return Iterator(Tail()); }
  297. /// Return iterator to the end.
  298. ConstIterator End() const { return ConstIterator(Tail()); }
  299. /// Return first key.
  300. const T& Front() const { return *Begin(); }
  301. /// Return last key.
  302. const T& Back() const { return *(--End()); }
  303. /// Return number of keys.
  304. unsigned Size() const { return size_; }
  305. /// Return whether set is empty.
  306. bool Empty() const { return size_ == 0; }
  307. private:
  308. /// Return the head node.
  309. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  310. /// Return the tail node.
  311. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  312. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  313. Node* FindNode(const T& key, unsigned hashKey) const
  314. {
  315. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  316. while (node)
  317. {
  318. if (node->key_ == key)
  319. return node;
  320. node = node->Down();
  321. }
  322. return 0;
  323. }
  324. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  325. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  326. {
  327. previous = 0;
  328. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  329. while (node)
  330. {
  331. if (node->key_ == key)
  332. return node;
  333. previous = node;
  334. node = node->Down();
  335. }
  336. return 0;
  337. }
  338. /// Insert a node into the list. Return the new node.
  339. Node* InsertNode(Node* dest, const T& key)
  340. {
  341. if (!dest)
  342. return 0;
  343. Node* newNode = ReserveNode(key);
  344. Node* prev = dest->Prev();
  345. newNode->next_ = dest;
  346. newNode->prev_ = prev;
  347. if (prev)
  348. prev->next_ = newNode;
  349. dest->prev_ = newNode;
  350. // Reassign the head node if necessary
  351. if (dest == Head())
  352. head_ = newNode;
  353. ++size_;
  354. return newNode;
  355. }
  356. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  357. Node* EraseNode(Node* node)
  358. {
  359. // The tail node can not be removed
  360. if (!node || node == tail_)
  361. return Tail();
  362. Node* prev = node->Prev();
  363. Node* next = node->Next();
  364. if (prev)
  365. prev->next_ = next;
  366. next->prev_ = prev;
  367. // Reassign the head node if necessary
  368. if (node == Head())
  369. head_ = next;
  370. FreeNode(node);
  371. --size_;
  372. return next;
  373. }
  374. /// Reserve a node.
  375. Node* ReserveNode()
  376. {
  377. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  378. new(newNode) Node();
  379. return newNode;
  380. }
  381. /// Reserve a node with specified key.
  382. Node* ReserveNode(const T& key)
  383. {
  384. if (!allocator_)
  385. allocator_ = AllocatorInitialize(sizeof(Node));
  386. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  387. new(newNode) Node(key);
  388. return newNode;
  389. }
  390. /// Free a node.
  391. void FreeNode(Node* node)
  392. {
  393. (node)->~Node();
  394. AllocatorFree(allocator_, node);
  395. }
  396. /// Reallocate and rehash the buckets.
  397. void Rehash()
  398. {
  399. delete[] ptrs_;
  400. ptrs_ = new HashNodeBase*[numBuckets_];
  401. for (unsigned i = 0; i < numBuckets_; ++i)
  402. ptrs_[i] = 0;
  403. for (Iterator it = Begin(); it != End(); ++it)
  404. {
  405. Node* node = reinterpret_cast<Node*>(it.ptr_);
  406. unsigned hashKey = MakeHash(*it) & (numBuckets_ - 1);
  407. node->down_ = ptrs_[hashKey];
  408. ptrs_[hashKey] = node;
  409. }
  410. }
  411. };