HashSet.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. //
  2. // Copyright (c) 2008-2014 the Urho3D project.
  3. //
  4. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5. // of this software and associated documentation files (the "Software"), to deal
  6. // in the Software without restriction, including without limitation the rights
  7. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. // copies of the Software, and to permit persons to whom the Software is
  9. // furnished to do so, subject to the following conditions:
  10. //
  11. // The above copyright notice and this permission notice shall be included in
  12. // all copies or substantial portions of the Software.
  13. //
  14. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  20. // THE SOFTWARE.
  21. //
  22. #pragma once
  23. #include "../Container/HashBase.h"
  24. #include "../Container/Sort.h"
  25. #include <cassert>
  26. namespace Urho3D
  27. {
  28. /// Hash set template class.
  29. template <class T> class HashSet : public HashBase
  30. {
  31. public:
  32. /// Hash set node.
  33. struct Node : public HashNodeBase
  34. {
  35. /// Construct undefined.
  36. Node()
  37. {
  38. }
  39. /// Construct with key.
  40. Node(const T& key) :
  41. key_(key)
  42. {
  43. }
  44. /// Key.
  45. T key_;
  46. /// Return next node.
  47. Node* Next() const { return static_cast<Node*>(next_); }
  48. /// Return previous node.
  49. Node* Prev() const { return static_cast<Node*>(prev_); }
  50. /// Return next node in the bucket.
  51. Node* Down() const { return static_cast<Node*>(down_); }
  52. };
  53. /// Hash set node iterator.
  54. struct Iterator : public HashIteratorBase
  55. {
  56. /// Construct.
  57. Iterator()
  58. {
  59. }
  60. /// Construct with a node pointer.
  61. Iterator(Node* ptr) :
  62. HashIteratorBase(ptr)
  63. {
  64. }
  65. /// Preincrement the pointer.
  66. Iterator& operator ++ () { GotoNext(); return *this; }
  67. /// Postincrement the pointer.
  68. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  69. /// Predecrement the pointer.
  70. Iterator& operator -- () { GotoPrev(); return *this; }
  71. /// Postdecrement the pointer.
  72. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  73. /// Point to the key.
  74. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  75. /// Dereference the key.
  76. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  77. };
  78. /// Hash set node const iterator.
  79. struct ConstIterator : public HashIteratorBase
  80. {
  81. /// Construct.
  82. ConstIterator()
  83. {
  84. }
  85. /// Construct with a node pointer.
  86. ConstIterator(Node* ptr) :
  87. HashIteratorBase(ptr)
  88. {
  89. }
  90. /// Construct from a non-const iterator.
  91. ConstIterator(const Iterator& rhs) :
  92. HashIteratorBase(rhs.ptr_)
  93. {
  94. }
  95. /// Assign from a non-const iterator.
  96. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  97. /// Preincrement the pointer.
  98. ConstIterator& operator ++ () { GotoNext(); return *this; }
  99. /// Postincrement the pointer.
  100. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  101. /// Predecrement the pointer.
  102. ConstIterator& operator -- () { GotoPrev(); return *this; }
  103. /// Postdecrement the pointer.
  104. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  105. /// Point to the key.
  106. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  107. /// Dereference the key.
  108. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  109. };
  110. /// Construct empty.
  111. HashSet()
  112. {
  113. // Reserve the tail node
  114. allocator_ = AllocatorInitialize(sizeof(Node));
  115. head_ = tail_ = ReserveNode();
  116. }
  117. /// Construct from another hash set.
  118. HashSet(const HashSet<T>& set)
  119. {
  120. // Reserve the tail node + initial capacity according to the set's size
  121. allocator_ = AllocatorInitialize(sizeof(Node), set.Size() + 1);
  122. head_ = tail_ = ReserveNode();
  123. *this = set;
  124. }
  125. /// Destruct.
  126. ~HashSet()
  127. {
  128. Clear();
  129. FreeNode(Tail());
  130. AllocatorUninitialize(allocator_);
  131. delete[] ptrs_;
  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 = Hash(key);
  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 = Hash(key);
  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. Return iterator to the next key.
  235. Iterator Erase(const Iterator& it)
  236. {
  237. if (!ptrs_ || !it.ptr_)
  238. return End();
  239. Node* node = static_cast<Node*>(it.ptr_);
  240. Node* next = node->Next();
  241. unsigned hashKey = Hash(node->key_);
  242. Node* previous = 0;
  243. Node* current = static_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. if (Size())
  261. {
  262. for (Iterator i = Begin(); i != End(); )
  263. {
  264. FreeNode(static_cast<Node*>(i++.ptr_));
  265. i.ptr_->prev_ = 0;
  266. }
  267. head_ = tail_;
  268. SetSize(0);
  269. }
  270. ResetPtrs();
  271. }
  272. /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
  273. void Sort()
  274. {
  275. unsigned numKeys = Size();
  276. if (!numKeys)
  277. return;
  278. Node** ptrs = new Node*[numKeys];
  279. Node* ptr = Head();
  280. for (unsigned i = 0; i < numKeys; ++i)
  281. {
  282. ptrs[i] = ptr;
  283. ptr = ptr->Next();
  284. }
  285. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  286. head_ = ptrs[0];
  287. ptrs[0]->prev_ = 0;
  288. for (unsigned i = 1; i < numKeys; ++i)
  289. {
  290. ptrs[i - 1]->next_ = ptrs[i];
  291. ptrs[i]->prev_ = ptrs[i - 1];
  292. }
  293. ptrs[numKeys - 1]->next_ = tail_;
  294. tail_->prev_ = ptrs[numKeys - 1];
  295. delete[] ptrs;
  296. }
  297. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  298. bool Rehash(unsigned numBuckets)
  299. {
  300. if (numBuckets == NumBuckets())
  301. return true;
  302. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  303. return false;
  304. // Check for being power of two
  305. unsigned check = numBuckets;
  306. while (!(check & 1))
  307. check >>= 1;
  308. if (check != 1)
  309. return false;
  310. AllocateBuckets(Size(), numBuckets);
  311. Rehash();
  312. return true;
  313. }
  314. /// Return iterator to the key, or end iterator if not found.
  315. Iterator Find(const T& key)
  316. {
  317. if (!ptrs_)
  318. return End();
  319. unsigned hashKey = Hash(key);
  320. Node* node = FindNode(key, hashKey);
  321. if (node)
  322. return Iterator(node);
  323. else
  324. return End();
  325. }
  326. /// Return const iterator to the key, or end iterator if not found.
  327. ConstIterator Find(const T& key) const
  328. {
  329. if (!ptrs_)
  330. return End();
  331. unsigned hashKey = Hash(key);
  332. Node* node = FindNode(key, hashKey);
  333. if (node)
  334. return ConstIterator(node);
  335. else
  336. return End();
  337. }
  338. /// Return whether contains a key.
  339. bool Contains(const T& key) const
  340. {
  341. if (!ptrs_)
  342. return false;
  343. unsigned hashKey = Hash(key);
  344. return FindNode(key, hashKey) != 0;
  345. }
  346. /// Return iterator to the beginning.
  347. Iterator Begin() { return Iterator(Head()); }
  348. /// Return iterator to the beginning.
  349. ConstIterator Begin() const { return ConstIterator(Head()); }
  350. /// Return iterator to the end.
  351. Iterator End() { return Iterator(Tail()); }
  352. /// Return iterator to the end.
  353. ConstIterator End() const { return ConstIterator(Tail()); }
  354. /// Return first key.
  355. const T& Front() const { return *Begin(); }
  356. /// Return last key.
  357. const T& Back() const { return *(--End()); }
  358. private:
  359. /// Return the head node.
  360. Node* Head() const { return static_cast<Node*>(head_); }
  361. /// Return the tail node.
  362. Node* Tail() const { return static_cast<Node*>(tail_); }
  363. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  364. Node* FindNode(const T& key, unsigned hashKey) const
  365. {
  366. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  367. while (node)
  368. {
  369. if (node->key_ == key)
  370. return node;
  371. node = node->Down();
  372. }
  373. return 0;
  374. }
  375. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  376. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  377. {
  378. previous = 0;
  379. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  380. while (node)
  381. {
  382. if (node->key_ == key)
  383. return node;
  384. previous = node;
  385. node = node->Down();
  386. }
  387. return 0;
  388. }
  389. /// Insert a node into the list. Return the new node.
  390. Node* InsertNode(Node* dest, const T& key)
  391. {
  392. if (!dest)
  393. return 0;
  394. Node* newNode = ReserveNode(key);
  395. Node* prev = dest->Prev();
  396. newNode->next_ = dest;
  397. newNode->prev_ = prev;
  398. if (prev)
  399. prev->next_ = newNode;
  400. dest->prev_ = newNode;
  401. // Reassign the head node if necessary
  402. if (dest == Head())
  403. head_ = newNode;
  404. SetSize(Size() + 1);
  405. return newNode;
  406. }
  407. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  408. Node* EraseNode(Node* node)
  409. {
  410. // The tail node can not be removed
  411. if (!node || node == tail_)
  412. return Tail();
  413. Node* prev = node->Prev();
  414. Node* next = node->Next();
  415. if (prev)
  416. prev->next_ = next;
  417. next->prev_ = prev;
  418. // Reassign the head node if necessary
  419. if (node == Head())
  420. head_ = next;
  421. FreeNode(node);
  422. SetSize(Size() - 1);
  423. return next;
  424. }
  425. /// Reserve a node.
  426. Node* ReserveNode()
  427. {
  428. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  429. new(newNode) Node();
  430. return newNode;
  431. }
  432. /// Reserve a node with specified key.
  433. Node* ReserveNode(const T& key)
  434. {
  435. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  436. new(newNode) Node(key);
  437. return newNode;
  438. }
  439. /// Free a node.
  440. void FreeNode(Node* node)
  441. {
  442. (node)->~Node();
  443. AllocatorFree(allocator_, node);
  444. }
  445. /// Rehash the buckets.
  446. void Rehash()
  447. {
  448. for (Iterator it = Begin(); it != End(); ++it)
  449. {
  450. Node* node = static_cast<Node*>(it.ptr_);
  451. unsigned hashKey = Hash(*it);
  452. node->down_ = Ptrs()[hashKey];
  453. Ptrs()[hashKey] = node;
  454. }
  455. }
  456. /// Compare two nodes.
  457. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
  458. /// Compute a hash based on the key and the bucket size
  459. unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
  460. };
  461. }