HashMap.h 19 KB

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