HashSet.h 14 KB

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