HashMap.h 18 KB

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