HashMap.h 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651
  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. delete[] ptrs_;
  167. }
  168. /// Assign a hash map.
  169. HashMap& operator = (const HashMap<T, U>& rhs)
  170. {
  171. Clear();
  172. Insert(rhs);
  173. return *this;
  174. }
  175. /// Add-assign a pair.
  176. HashMap& operator += (const Pair<T, U>& rhs)
  177. {
  178. Insert(rhs);
  179. return *this;
  180. }
  181. /// Add-assign a hash map.
  182. HashMap& operator += (const HashMap<T, U>& rhs)
  183. {
  184. Insert(rhs);
  185. return *this;
  186. }
  187. /// Test for equality with another hash map.
  188. bool operator == (const HashMap<T, U>& rhs) const
  189. {
  190. if (rhs.Size() != Size())
  191. return false;
  192. ConstIterator i = Begin();
  193. while (i != End())
  194. {
  195. ConstIterator j = rhs.Find(i->first_);
  196. if (j == rhs.End() || j->second_ != i->second_)
  197. return false;
  198. ++i;
  199. }
  200. return true;
  201. }
  202. /// Test for inequality with another hash map.
  203. bool operator != (const HashMap<T, U>& rhs) const
  204. {
  205. if (rhs.Size() != Size())
  206. return true;
  207. ConstIterator i = Begin();
  208. while (i != End())
  209. {
  210. ConstIterator j = rhs.Find(i->first_);
  211. if (j == rhs.End() || j->second_ != i->second_)
  212. return true;
  213. ++i;
  214. }
  215. return false;
  216. }
  217. /// Index the map. Create a new pair if key not found.
  218. U& operator [] (const T& key)
  219. {
  220. if (!ptrs_)
  221. return InsertNode(key, U(), false)->pair_.second_;
  222. unsigned hashKey = Hash(key);
  223. Node* node = FindNode(key, hashKey);
  224. if (node)
  225. return node->pair_.second_;
  226. else
  227. return InsertNode(key, U(), false)->pair_.second_;
  228. }
  229. /// Insert a pair. Return an iterator to it.
  230. Iterator Insert(const Pair<T, U>& pair)
  231. {
  232. return Iterator(InsertNode(pair.first_, pair.second_));
  233. }
  234. /// Insert a map.
  235. void Insert(const HashMap<T, U>& map)
  236. {
  237. ConstIterator it = map.Begin();
  238. ConstIterator end = map.End();
  239. while (it != end)
  240. {
  241. InsertNode(it->first_, it->second_);
  242. ++it;
  243. }
  244. }
  245. /// Insert a pair by iterator. Return iterator to the value.
  246. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
  247. /// Insert a range by iterators.
  248. void Insert(const ConstIterator& start, const ConstIterator& end)
  249. {
  250. ConstIterator it = start;
  251. while (it != end)
  252. InsertNode(*it++);
  253. }
  254. /// Erase a pair by key. Return true if was found.
  255. bool Erase(const T& key)
  256. {
  257. if (!ptrs_)
  258. return false;
  259. unsigned hashKey = Hash(key);
  260. Node* previous;
  261. Node* node = FindNode(key, hashKey, previous);
  262. if (!node)
  263. return false;
  264. if (previous)
  265. previous->down_ = node->down_;
  266. else
  267. Ptrs()[hashKey] = node->down_;
  268. EraseNode(node);
  269. return true;
  270. }
  271. /// Erase a pair by iterator. Return iterator to the next pair.
  272. Iterator Erase(const Iterator& it)
  273. {
  274. if (!ptrs_ || !it.ptr_)
  275. return End();
  276. Node* node = static_cast<Node*>(it.ptr_);
  277. Node* next = node->Next();
  278. unsigned hashKey = Hash(node->pair_.first_);
  279. Node* previous = 0;
  280. Node* current = static_cast<Node*>(Ptrs()[hashKey]);
  281. while (current && current != node)
  282. {
  283. previous = current;
  284. current = current->Down();
  285. }
  286. assert(current == node);
  287. if (previous)
  288. previous->down_ = node->down_;
  289. else
  290. Ptrs()[hashKey] = node->down_;
  291. EraseNode(node);
  292. return Iterator(next);
  293. }
  294. /// Clear the map.
  295. void Clear()
  296. {
  297. if (Size())
  298. {
  299. for (Iterator i = Begin(); i != End(); )
  300. {
  301. FreeNode(static_cast<Node*>(i++.ptr_));
  302. i.ptr_->prev_ = 0;
  303. }
  304. head_ = tail_;
  305. SetSize(0);
  306. }
  307. ResetPtrs();
  308. }
  309. /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
  310. void Sort()
  311. {
  312. unsigned numKeys = Size();
  313. if (!numKeys)
  314. return;
  315. Node** ptrs = new Node*[numKeys];
  316. Node* ptr = Head();
  317. for (unsigned i = 0; i < numKeys; ++i)
  318. {
  319. ptrs[i] = ptr;
  320. ptr = ptr->Next();
  321. }
  322. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  323. head_ = ptrs[0];
  324. ptrs[0]->prev_ = 0;
  325. for (unsigned i = 1; i < numKeys; ++i)
  326. {
  327. ptrs[i - 1]->next_ = ptrs[i];
  328. ptrs[i]->prev_ = ptrs[i - 1];
  329. }
  330. ptrs[numKeys - 1]->next_ = tail_;
  331. tail_->prev_ = ptrs[numKeys - 1];
  332. delete[] ptrs;
  333. }
  334. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  335. bool Rehash(unsigned numBuckets)
  336. {
  337. if (numBuckets == NumBuckets())
  338. return true;
  339. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  340. return false;
  341. // Check for being power of two
  342. unsigned check = numBuckets;
  343. while (!(check & 1))
  344. check >>= 1;
  345. if (check != 1)
  346. return false;
  347. AllocateBuckets(Size(), numBuckets);
  348. Rehash();
  349. return true;
  350. }
  351. /// Return iterator to the pair with key, or end iterator if not found.
  352. Iterator Find(const T& key)
  353. {
  354. if (!ptrs_)
  355. return End();
  356. unsigned hashKey = Hash(key);
  357. Node* node = FindNode(key, hashKey);
  358. if (node)
  359. return Iterator(node);
  360. else
  361. return End();
  362. }
  363. /// Return const iterator to the pair with key, or end iterator if not found.
  364. ConstIterator Find(const T& key) const
  365. {
  366. if (!ptrs_)
  367. return End();
  368. unsigned hashKey = Hash(key);
  369. Node* node = FindNode(key, hashKey);
  370. if (node)
  371. return ConstIterator(node);
  372. else
  373. return End();
  374. }
  375. /// Return whether contains a pair with key.
  376. bool Contains(const T& key) const
  377. {
  378. if (!ptrs_)
  379. return false;
  380. unsigned hashKey = Hash(key);
  381. return FindNode(key, hashKey) != 0;
  382. }
  383. /// Return all the keys.
  384. Vector<T> Keys() const
  385. {
  386. Vector<T> result;
  387. result.Reserve(Size());
  388. for (ConstIterator i = Begin(); i != End(); ++i)
  389. result.Push(i->first_);
  390. return result;
  391. }
  392. /// Return all the values.
  393. Vector<U> Values() const
  394. {
  395. Vector<U> result;
  396. result.Reserve(Size());
  397. for (ConstIterator i = Begin(); i != End(); ++i)
  398. result.Push(i->second_);
  399. return result;
  400. }
  401. /// Return iterator to the beginning.
  402. Iterator Begin() { return Iterator(Head()); }
  403. /// Return iterator to the beginning.
  404. ConstIterator Begin() const { return ConstIterator(Head()); }
  405. /// Return iterator to the end.
  406. Iterator End() { return Iterator(Tail()); }
  407. /// Return iterator to the end.
  408. ConstIterator End() const { return ConstIterator(Tail()); }
  409. /// Return first key.
  410. const T& Front() const { return *Begin(); }
  411. /// Return last key.
  412. const T& Back() const { return *(--End()); }
  413. private:
  414. /// Return the head node.
  415. Node* Head() const { return static_cast<Node*>(head_); }
  416. /// Return the tail node.
  417. Node* Tail() const { return static_cast<Node*>(tail_); }
  418. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  419. Node* FindNode(const T& key, unsigned hashKey) const
  420. {
  421. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  422. while (node)
  423. {
  424. if (node->pair_.first_ == key)
  425. return node;
  426. node = node->Down();
  427. }
  428. return 0;
  429. }
  430. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  431. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  432. {
  433. previous = 0;
  434. Node* node = static_cast<Node*>(Ptrs()[hashKey]);
  435. while (node)
  436. {
  437. if (node->pair_.first_ == key)
  438. return node;
  439. previous = node;
  440. node = node->Down();
  441. }
  442. return 0;
  443. }
  444. /// Insert a key and value and return either the new or existing node.
  445. Node* InsertNode(const T& key, const U& value, bool findExisting = true)
  446. {
  447. // If no pointers yet, allocate with minimum bucket count
  448. if (!ptrs_)
  449. {
  450. AllocateBuckets(Size(), MIN_BUCKETS);
  451. Rehash();
  452. }
  453. unsigned hashKey = Hash(key);
  454. if (findExisting)
  455. {
  456. // If exists, just change the value
  457. Node* existing = FindNode(key, hashKey);
  458. if (existing)
  459. {
  460. existing->pair_.second_ = value;
  461. return existing;
  462. }
  463. }
  464. Node* newNode = InsertNode(Tail(), key, value);
  465. newNode->down_ = Ptrs()[hashKey];
  466. Ptrs()[hashKey] = newNode;
  467. // Rehash if the maximum load factor has been exceeded
  468. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  469. {
  470. AllocateBuckets(Size(), NumBuckets() << 1);
  471. Rehash();
  472. }
  473. return newNode;
  474. }
  475. /// Insert a node into the list. Return the new node.
  476. Node* InsertNode(Node* dest, const T& key, const U& value)
  477. {
  478. if (!dest)
  479. return 0;
  480. Node* newNode = ReserveNode(key, value);
  481. Node* prev = dest->Prev();
  482. newNode->next_ = dest;
  483. newNode->prev_ = prev;
  484. if (prev)
  485. prev->next_ = newNode;
  486. dest->prev_ = newNode;
  487. // Reassign the head node if necessary
  488. if (dest == Head())
  489. head_ = newNode;
  490. SetSize(Size() + 1);
  491. return newNode;
  492. }
  493. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  494. Node* EraseNode(Node* node)
  495. {
  496. // The tail node can not be removed
  497. if (!node || node == tail_)
  498. return Tail();
  499. Node* prev = node->Prev();
  500. Node* next = node->Next();
  501. if (prev)
  502. prev->next_ = next;
  503. next->prev_ = prev;
  504. // Reassign the head node if necessary
  505. if (node == Head())
  506. head_ = next;
  507. FreeNode(node);
  508. SetSize(Size() - 1);
  509. return next;
  510. }
  511. /// Reserve a node.
  512. Node* ReserveNode()
  513. {
  514. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  515. new(newNode) Node();
  516. return newNode;
  517. }
  518. /// Reserve a node with specified key and value.
  519. Node* ReserveNode(const T& key, const U& value)
  520. {
  521. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  522. new(newNode) Node(key, value);
  523. return newNode;
  524. }
  525. /// Free a node.
  526. void FreeNode(Node* node)
  527. {
  528. (node)->~Node();
  529. AllocatorFree(allocator_, node);
  530. }
  531. /// Rehash the buckets.
  532. void Rehash()
  533. {
  534. for (Iterator i = Begin(); i != End(); ++i)
  535. {
  536. Node* node = static_cast<Node*>(i.ptr_);
  537. unsigned hashKey = Hash(i->first_);
  538. node->down_ = Ptrs()[hashKey];
  539. Ptrs()[hashKey] = node;
  540. }
  541. }
  542. /// Compare two nodes.
  543. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
  544. /// Compute a hash based on the key and the bucket size
  545. unsigned Hash(const T& key) const { return MakeHash(key) & (NumBuckets() - 1); }
  546. };
  547. }