HashMap.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  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 "Pair.h"
  25. #include "Sort.h"
  26. #include "Vector.h"
  27. #include <cassert>
  28. namespace Urho3D
  29. {
  30. /// Hash map template class.
  31. template <class T, class U> class HashMap : public HashBase
  32. {
  33. public:
  34. /// Hash map key-value pair with const key.
  35. class KeyValue
  36. {
  37. public:
  38. /// Construct with default key.
  39. KeyValue() :
  40. first_(T())
  41. {
  42. }
  43. /// Construct with key and value.
  44. KeyValue(const T& first, const U& second) :
  45. first_(first),
  46. second_(second)
  47. {
  48. }
  49. /// Copy-construct.
  50. KeyValue(const KeyValue& value) :
  51. first_(value.first_),
  52. second_(value.second_)
  53. {
  54. }
  55. /// Test for equality with another pair.
  56. bool operator == (const KeyValue& rhs) const { return first_ == rhs.first_ && second_ == rhs.second_; }
  57. /// Test for inequality with another pair.
  58. bool operator != (const KeyValue& rhs) const { return first_ != rhs.first_ || second_ != rhs.second_; }
  59. /// Key.
  60. const T first_;
  61. /// Value.
  62. U second_;
  63. private:
  64. /// Prevent assignment.
  65. KeyValue& operator = (const KeyValue& rhs);
  66. };
  67. /// Hash map node.
  68. struct Node : public HashNodeBase
  69. {
  70. /// Construct undefined.
  71. Node()
  72. {
  73. }
  74. /// Construct with key and value.
  75. Node(const T& key, const U& value) :
  76. pair_(key, value)
  77. {
  78. }
  79. /// Key-value pair.
  80. KeyValue pair_;
  81. /// Return next node.
  82. Node* Next() const { return static_cast<Node*>(next_); }
  83. /// Return previous node.
  84. Node* Prev() const { return static_cast<Node*>(prev_); }
  85. /// Return next node in the bucket.
  86. Node* Down() const { return static_cast<Node*>(down_); }
  87. };
  88. /// Hash map node iterator.
  89. struct Iterator : public HashIteratorBase
  90. {
  91. /// Construct.
  92. Iterator()
  93. {
  94. }
  95. /// Construct with a node pointer.
  96. Iterator(Node* ptr) :
  97. HashIteratorBase(ptr)
  98. {
  99. }
  100. /// Preincrement the pointer.
  101. Iterator& operator ++ () { GotoNext(); return *this; }
  102. /// Postincrement the pointer.
  103. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  104. /// Predecrement the pointer.
  105. Iterator& operator -- () { GotoPrev(); return *this; }
  106. /// Postdecrement the pointer.
  107. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  108. /// Point to the pair.
  109. KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
  110. /// Dereference the pair.
  111. KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
  112. };
  113. /// Hash map node const iterator.
  114. struct ConstIterator : public HashIteratorBase
  115. {
  116. /// Construct.
  117. ConstIterator()
  118. {
  119. }
  120. /// Construct with a node pointer.
  121. ConstIterator(Node* ptr) :
  122. HashIteratorBase(ptr)
  123. {
  124. }
  125. /// Construct from a non-const iterator.
  126. ConstIterator(const Iterator& rhs) :
  127. HashIteratorBase(rhs.ptr_)
  128. {
  129. }
  130. /// Assign from a non-const iterator.
  131. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  132. /// Preincrement the pointer.
  133. ConstIterator& operator ++ () { GotoNext(); return *this; }
  134. /// Postincrement the pointer.
  135. ConstIterator operator ++ (int) { ConstIterator it = *this; GotoNext(); return it; }
  136. /// Predecrement the pointer.
  137. ConstIterator& operator -- () { GotoPrev(); return *this; }
  138. /// Postdecrement the pointer.
  139. ConstIterator operator -- (int) { ConstIterator it = *this; GotoPrev(); return it; }
  140. /// Point to the pair.
  141. const KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
  142. /// Dereference the pair.
  143. const KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
  144. };
  145. /// Construct empty.
  146. HashMap()
  147. {
  148. // Reserve the tail node
  149. allocator_ = AllocatorInitialize(sizeof(Node));
  150. head_ = tail_ = ReserveNode();
  151. }
  152. /// Construct from another hash map.
  153. HashMap(const HashMap<T, U>& map)
  154. {
  155. // Reserve the tail node + initial capacity according to the map's size
  156. allocator_ = AllocatorInitialize(sizeof(Node), map.Size() + 1);
  157. head_ = tail_ = ReserveNode();
  158. *this = map;
  159. }
  160. /// Destruct.
  161. ~HashMap()
  162. {
  163. Clear();
  164. FreeNode(Tail());
  165. AllocatorUninitialize(allocator_);
  166. }
  167. /// Assign a hash map.
  168. HashMap& operator = (const HashMap<T, U>& rhs)
  169. {
  170. Clear();
  171. Insert(rhs);
  172. return *this;
  173. }
  174. /// Add-assign a pair.
  175. HashMap& operator += (const Pair<T, U>& rhs)
  176. {
  177. Insert(rhs);
  178. return *this;
  179. }
  180. /// Add-assign a hash map.
  181. HashMap& operator += (const HashMap<T, U>& rhs)
  182. {
  183. Insert(rhs);
  184. return *this;
  185. }
  186. /// Test for equality with another hash map.
  187. bool operator == (const HashMap<T, U>& rhs) const
  188. {
  189. if (rhs.Size() != Size())
  190. return false;
  191. ConstIterator i = Begin();
  192. while (i != End())
  193. {
  194. ConstIterator j = rhs.Find(i->first_);
  195. if (j == rhs.End() || j->second_ != i->second_)
  196. return false;
  197. ++i;
  198. }
  199. return true;
  200. }
  201. /// Test for inequality with another hash map.
  202. bool operator != (const HashMap<T, U>& rhs) const
  203. {
  204. if (rhs.Size() != Size())
  205. return true;
  206. ConstIterator i = Begin();
  207. while (i != End())
  208. {
  209. ConstIterator j = rhs.Find(i->first_);
  210. if (j == rhs.End() || j->second_ != i->second_)
  211. return true;
  212. ++i;
  213. }
  214. return false;
  215. }
  216. /// Index the map. Create a new pair if key not found.
  217. U& operator [] (const T& key)
  218. {
  219. if (!ptrs_)
  220. return InsertNode(key, U(), false)->pair_.second_;
  221. unsigned hashKey = Hash(key);
  222. Node* node = FindNode(key, hashKey);
  223. if (node)
  224. return node->pair_.second_;
  225. else
  226. return InsertNode(key, U(), false)->pair_.second_;
  227. }
  228. /// Insert a pair. Return an iterator to it.
  229. Iterator Insert(const Pair<T, U>& pair)
  230. {
  231. return Iterator(InsertNode(pair.first_, pair.second_));
  232. }
  233. /// Insert a map.
  234. void Insert(const HashMap<T, U>& map)
  235. {
  236. ConstIterator it = map.Begin();
  237. ConstIterator end = map.End();
  238. while (it != end)
  239. {
  240. InsertNode(it->first_, it->second_);
  241. ++it;
  242. }
  243. }
  244. /// Insert a pair by iterator. Return iterator to the value.
  245. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
  246. /// Insert a range by iterators.
  247. void Insert(const ConstIterator& start, const ConstIterator& end)
  248. {
  249. ConstIterator it = start;
  250. while (it != end)
  251. InsertNode(*it++);
  252. }
  253. /// Erase a pair by key. Return true if was found.
  254. bool Erase(const T& key)
  255. {
  256. if (!ptrs_)
  257. return false;
  258. unsigned hashKey = Hash(key);
  259. Node* previous;
  260. Node* node = FindNode(key, hashKey, previous);
  261. if (!node)
  262. return false;
  263. if (previous)
  264. previous->down_ = node->down_;
  265. else
  266. Ptrs()[hashKey] = node->down_;
  267. EraseNode(node);
  268. return true;
  269. }
  270. /// Erase a pair by iterator. Return iterator to the next pair.
  271. Iterator Erase(const Iterator& it)
  272. {
  273. if (!ptrs_ || !it.ptr_)
  274. return End();
  275. Node* node = static_cast<Node*>(it.ptr_);
  276. Node* next = node->Next();
  277. unsigned hashKey = Hash(node->pair_.first_);
  278. Node* previous = 0;
  279. Node* current = static_cast<Node*>(Ptrs()[hashKey]);
  280. while (current && current != node)
  281. {
  282. previous = current;
  283. current = current->Down();
  284. }
  285. assert(current == node);
  286. if (previous)
  287. previous->down_ = node->down_;
  288. else
  289. Ptrs()[hashKey] = node->down_;
  290. EraseNode(node);
  291. return Iterator(next);
  292. }
  293. /// Clear the map.
  294. void Clear()
  295. {
  296. if (Size())
  297. {
  298. for (Iterator i = Begin(); i != End(); )
  299. {
  300. FreeNode(static_cast<Node*>(i++.ptr_));
  301. i.ptr_->prev_ = 0;
  302. }
  303. head_ = tail_;
  304. SetSize(0);
  305. }
  306. ResetPtrs();
  307. }
  308. /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
  309. void Sort()
  310. {
  311. unsigned numKeys = Size();
  312. if (!numKeys)
  313. return;
  314. Node** ptrs = new Node*[numKeys];
  315. Node* ptr = Head();
  316. for (unsigned i = 0; i < numKeys; ++i)
  317. {
  318. ptrs[i] = ptr;
  319. ptr = ptr->Next();
  320. }
  321. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  322. head_ = ptrs[0];
  323. ptrs[0]->prev_ = 0;
  324. for (unsigned i = 1; i < numKeys; ++i)
  325. {
  326. ptrs[i - 1]->next_ = ptrs[i];
  327. ptrs[i]->prev_ = ptrs[i - 1];
  328. }
  329. ptrs[numKeys - 1]->next_ = tail_;
  330. tail_->prev_ = ptrs[numKeys - 1];
  331. delete[] ptrs;
  332. }
  333. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  334. bool Rehash(unsigned numBuckets)
  335. {
  336. if (numBuckets == NumBuckets())
  337. return true;
  338. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  339. return false;
  340. // Check for being power of two
  341. unsigned check = numBuckets;
  342. while (!(check & 1))
  343. check >>= 1;
  344. if (check != 1)
  345. return false;
  346. AllocateBuckets(Size(), numBuckets);
  347. Rehash();
  348. return true;
  349. }
  350. /// Return iterator to the pair with key, or end iterator if not found.
  351. Iterator Find(const T& key)
  352. {
  353. if (!ptrs_)
  354. return End();
  355. unsigned hashKey = Hash(key);
  356. Node* node = FindNode(key, hashKey);
  357. if (node)
  358. return Iterator(node);
  359. else
  360. return End();
  361. }
  362. /// Return const iterator to the pair with key, or end iterator if not found.
  363. ConstIterator Find(const T& key) const
  364. {
  365. if (!ptrs_)
  366. return End();
  367. unsigned hashKey = Hash(key);
  368. Node* node = FindNode(key, hashKey);
  369. if (node)
  370. return ConstIterator(node);
  371. else
  372. return End();
  373. }
  374. /// Return whether contains a pair with key.
  375. bool Contains(const T& key) const
  376. {
  377. if (!ptrs_)
  378. return false;
  379. unsigned hashKey = Hash(key);
  380. return FindNode(key, hashKey) != 0;
  381. }
  382. /// Return all the keys.
  383. Vector<T> Keys() const
  384. {
  385. Vector<T> result;
  386. result.Reserve(Size());
  387. for (ConstIterator i = Begin(); i != End(); ++i)
  388. result.Push(i->first_);
  389. return result;
  390. }
  391. /// Return iterator to the beginning.
  392. Iterator Begin() { return Iterator(Head()); }
  393. /// Return iterator to the beginning.
  394. ConstIterator Begin() const { return ConstIterator(Head()); }
  395. /// Return iterator to the end.
  396. Iterator End() { return Iterator(Tail()); }
  397. /// Return iterator to the end.
  398. ConstIterator End() const { return ConstIterator(Tail()); }
  399. /// Return first key.
  400. const T& Front() const { return *Begin(); }
  401. /// Return last key.
  402. const T& Back() const { return *(--End()); }
  403. private:
  404. /// Return the head node.
  405. Node* Head() const { return static_cast<Node*>(head_); }
  406. /// Return the tail node.
  407. Node* Tail() const { return static_cast<Node*>(tail_); }
  408. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  409. Node* FindNode(const T& key, unsigned hashKey) const
  410. {
  411. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  412. while (node)
  413. {
  414. if (node->pair_.first_ == key)
  415. return node;
  416. node = node->Down();
  417. }
  418. return 0;
  419. }
  420. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  421. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  422. {
  423. previous = 0;
  424. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  425. while (node)
  426. {
  427. if (node->pair_.first_ == key)
  428. return node;
  429. previous = node;
  430. node = node->Down();
  431. }
  432. return 0;
  433. }
  434. /// Insert a key and value and return either the new or existing node.
  435. Node* InsertNode(const T& key, const U& value, bool findExisting = true)
  436. {
  437. // If no pointers yet, allocate with minimum bucket count
  438. if (!ptrs_)
  439. {
  440. AllocateBuckets(Size(), MIN_BUCKETS);
  441. Rehash();
  442. }
  443. unsigned hashKey = Hash(key);
  444. if (findExisting)
  445. {
  446. // If exists, just change the value
  447. Node* existing = FindNode(key, hashKey);
  448. if (existing)
  449. {
  450. existing->pair_.second_ = value;
  451. return existing;
  452. }
  453. }
  454. Node* newNode = InsertNode(Tail(), key, value);
  455. newNode->down_ = Ptrs()[hashKey];
  456. Ptrs()[hashKey] = newNode;
  457. // Rehash if the maximum load factor has been exceeded
  458. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  459. {
  460. AllocateBuckets(Size(), NumBuckets() << 1);
  461. Rehash();
  462. }
  463. return newNode;
  464. }
  465. /// Insert a node into the list. Return the new node.
  466. Node* InsertNode(Node* dest, const T& key, const U& value)
  467. {
  468. if (!dest)
  469. return 0;
  470. Node* newNode = ReserveNode(key, value);
  471. Node* prev = dest->Prev();
  472. newNode->next_ = dest;
  473. newNode->prev_ = prev;
  474. if (prev)
  475. prev->next_ = newNode;
  476. dest->prev_ = newNode;
  477. // Reassign the head node if necessary
  478. if (dest == Head())
  479. head_ = newNode;
  480. SetSize(Size() + 1);
  481. return newNode;
  482. }
  483. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  484. Node* EraseNode(Node* node)
  485. {
  486. // The tail node can not be removed
  487. if (!node || node == tail_)
  488. return Tail();
  489. Node* prev = node->Prev();
  490. Node* next = node->Next();
  491. if (prev)
  492. prev->next_ = next;
  493. next->prev_ = prev;
  494. // Reassign the head node if necessary
  495. if (node == Head())
  496. head_ = next;
  497. FreeNode(node);
  498. SetSize(Size() - 1);
  499. return next;
  500. }
  501. /// Reserve a node.
  502. Node* ReserveNode()
  503. {
  504. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  505. new(newNode) Node();
  506. return newNode;
  507. }
  508. /// Reserve a node with specified key and value.
  509. Node* ReserveNode(const T& key, const U& value)
  510. {
  511. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  512. new(newNode) Node(key, value);
  513. return newNode;
  514. }
  515. /// Free a node.
  516. void FreeNode(Node* node)
  517. {
  518. (node)->~Node();
  519. AllocatorFree(allocator_, node);
  520. }
  521. /// Rehash the buckets.
  522. void Rehash()
  523. {
  524. for (Iterator i = Begin(); i != End(); ++i)
  525. {
  526. Node* node = static_cast<Node*>(i.ptr_);
  527. unsigned hashKey = Hash(i->first_);
  528. node->down_ = Ptrs()[hashKey];
  529. Ptrs()[hashKey] = node;
  530. }
  531. }
  532. /// Compare two nodes.
  533. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
  534. /// Compute a hash based on the key and the bucket size
  535. unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
  536. };
  537. }