HashMap.h 21 KB

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