HashSet.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  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 "HashBase.h"
  24. #include "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. }
  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.
  152. bool operator == (const HashSet<T>& rhs) const
  153. {
  154. if (rhs.Size() != Size())
  155. return false;
  156. ConstIterator it = Begin();
  157. while (it != End())
  158. {
  159. if (!rhs.Contains(*it))
  160. return false;
  161. ++it;
  162. }
  163. return true;
  164. }
  165. /// Test for inequality with another hash set.
  166. bool operator != (const HashSet<T>& rhs) const
  167. {
  168. if (rhs.Size() != Size())
  169. return true;
  170. ConstIterator it = Begin();
  171. while (it != End())
  172. {
  173. if (!rhs.Contains(*it))
  174. return true;
  175. ++it;
  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. AllocateBuckets(Size(), MIN_BUCKETS);
  186. Rehash();
  187. }
  188. unsigned hashKey = Hash(key);
  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. AllocateBuckets(Size(), 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 (!ptrs_)
  220. return false;
  221. unsigned hashKey = Hash(key);
  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. Return iterator to the next key.
  234. Iterator Erase(const Iterator& it)
  235. {
  236. if (!ptrs_ || !it.ptr_)
  237. return End();
  238. Node* node = static_cast<Node*>(it.ptr_);
  239. Node* next = node->Next();
  240. unsigned hashKey = Hash(node->key_);
  241. Node* previous = 0;
  242. Node* current = static_cast<Node*>(Ptrs()[hashKey]);
  243. while (current && current != node)
  244. {
  245. previous = current;
  246. current = current->Down();
  247. }
  248. assert(current == node);
  249. if (previous)
  250. previous->down_ = node->down_;
  251. else
  252. Ptrs()[hashKey] = node->down_;
  253. EraseNode(node);
  254. return Iterator(next);
  255. }
  256. /// Clear the set.
  257. void Clear()
  258. {
  259. if (Size())
  260. {
  261. for (Iterator i = Begin(); i != End(); )
  262. {
  263. FreeNode(static_cast<Node*>(i++.ptr_));
  264. i.ptr_->prev_ = 0;
  265. }
  266. head_ = tail_;
  267. SetSize(0);
  268. }
  269. ResetPtrs();
  270. }
  271. /// Sort keys. After sorting the set can be iterated in order until new elements are inserted.
  272. void Sort()
  273. {
  274. unsigned numKeys = Size();
  275. if (!numKeys)
  276. return;
  277. Node** ptrs = new Node*[numKeys];
  278. Node* ptr = Head();
  279. for (unsigned i = 0; i < numKeys; ++i)
  280. {
  281. ptrs[i] = ptr;
  282. ptr = ptr->Next();
  283. }
  284. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  285. head_ = ptrs[0];
  286. ptrs[0]->prev_ = 0;
  287. for (unsigned i = 1; i < numKeys; ++i)
  288. {
  289. ptrs[i - 1]->next_ = ptrs[i];
  290. ptrs[i]->prev_ = ptrs[i - 1];
  291. }
  292. ptrs[numKeys - 1]->next_ = tail_;
  293. tail_->prev_ = ptrs[numKeys - 1];
  294. delete[] ptrs;
  295. }
  296. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  297. bool Rehash(unsigned numBuckets)
  298. {
  299. if (numBuckets == NumBuckets())
  300. return true;
  301. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  302. return false;
  303. // Check for being power of two
  304. unsigned check = numBuckets;
  305. while (!(check & 1))
  306. check >>= 1;
  307. if (check != 1)
  308. return false;
  309. AllocateBuckets(Size(), numBuckets);
  310. Rehash();
  311. return true;
  312. }
  313. /// Return iterator to the key, or end iterator if not found.
  314. Iterator Find(const T& key)
  315. {
  316. if (!ptrs_)
  317. return End();
  318. unsigned hashKey = Hash(key);
  319. Node* node = FindNode(key, hashKey);
  320. if (node)
  321. return Iterator(node);
  322. else
  323. return End();
  324. }
  325. /// Return const iterator to the key, or end iterator if not found.
  326. ConstIterator Find(const T& key) const
  327. {
  328. if (!ptrs_)
  329. return End();
  330. unsigned hashKey = Hash(key);
  331. Node* node = FindNode(key, hashKey);
  332. if (node)
  333. return ConstIterator(node);
  334. else
  335. return End();
  336. }
  337. /// Return whether contains a key.
  338. bool Contains(const T& key) const
  339. {
  340. if (!ptrs_)
  341. return false;
  342. unsigned hashKey = Hash(key);
  343. return FindNode(key, hashKey) != 0;
  344. }
  345. /// Return iterator to the beginning.
  346. Iterator Begin() { return Iterator(Head()); }
  347. /// Return iterator to the beginning.
  348. ConstIterator Begin() const { return ConstIterator(Head()); }
  349. /// Return iterator to the end.
  350. Iterator End() { return Iterator(Tail()); }
  351. /// Return iterator to the end.
  352. ConstIterator End() const { return ConstIterator(Tail()); }
  353. /// Return first key.
  354. const T& Front() const { return *Begin(); }
  355. /// Return last key.
  356. const T& Back() const { return *(--End()); }
  357. private:
  358. /// Return the head node.
  359. Node* Head() const { return static_cast<Node*>(head_); }
  360. /// Return the tail node.
  361. Node* Tail() const { return static_cast<Node*>(tail_); }
  362. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  363. Node* FindNode(const T& key, unsigned hashKey) const
  364. {
  365. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  366. while (node)
  367. {
  368. if (node->key_ == key)
  369. return node;
  370. node = node->Down();
  371. }
  372. return 0;
  373. }
  374. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  375. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  376. {
  377. previous = 0;
  378. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  379. while (node)
  380. {
  381. if (node->key_ == key)
  382. return node;
  383. previous = node;
  384. node = node->Down();
  385. }
  386. return 0;
  387. }
  388. /// Insert a node into the list. Return the new node.
  389. Node* InsertNode(Node* dest, const T& key)
  390. {
  391. if (!dest)
  392. return 0;
  393. Node* newNode = ReserveNode(key);
  394. Node* prev = dest->Prev();
  395. newNode->next_ = dest;
  396. newNode->prev_ = prev;
  397. if (prev)
  398. prev->next_ = newNode;
  399. dest->prev_ = newNode;
  400. // Reassign the head node if necessary
  401. if (dest == Head())
  402. head_ = newNode;
  403. SetSize(Size() + 1);
  404. return newNode;
  405. }
  406. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  407. Node* EraseNode(Node* node)
  408. {
  409. // The tail node can not be removed
  410. if (!node || node == tail_)
  411. return Tail();
  412. Node* prev = node->Prev();
  413. Node* next = node->Next();
  414. if (prev)
  415. prev->next_ = next;
  416. next->prev_ = prev;
  417. // Reassign the head node if necessary
  418. if (node == Head())
  419. head_ = next;
  420. FreeNode(node);
  421. SetSize(Size() - 1);
  422. return next;
  423. }
  424. /// Reserve a node.
  425. Node* ReserveNode()
  426. {
  427. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  428. new(newNode) Node();
  429. return newNode;
  430. }
  431. /// Reserve a node with specified key.
  432. Node* ReserveNode(const T& key)
  433. {
  434. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  435. new(newNode) Node(key);
  436. return newNode;
  437. }
  438. /// Free a node.
  439. void FreeNode(Node* node)
  440. {
  441. (node)->~Node();
  442. AllocatorFree(allocator_, node);
  443. }
  444. /// Rehash the buckets.
  445. void Rehash()
  446. {
  447. for (Iterator it = Begin(); it != End(); ++it)
  448. {
  449. Node* node = static_cast<Node*>(it.ptr_);
  450. unsigned hashKey = Hash(*it);
  451. node->down_ = Ptrs()[hashKey];
  452. Ptrs()[hashKey] = node;
  453. }
  454. }
  455. /// Compare two nodes.
  456. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->key_ < rhs->key_; }
  457. /// Compute a hash based on the key and the bucket size
  458. unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
  459. };
  460. }