HashMap.h 18 KB

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