HashMap.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2012 Lasse Oorni
  4. //
  5. // Permission is hereby granted, free of charge, to any person obtaining a copy
  6. // of this software and associated documentation files (the "Software"), to deal
  7. // in the Software without restriction, including without limitation the rights
  8. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  9. // copies of the Software, and to permit persons to whom the Software is
  10. // furnished to do so, subject to the following conditions:
  11. //
  12. // The above copyright notice and this permission notice shall be included in
  13. // all copies or substantial portions of the Software.
  14. //
  15. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  16. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  17. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  18. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  19. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  20. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  21. // THE SOFTWARE.
  22. //
  23. #pragma once
  24. #include "HashBase.h"
  25. #include "Pair.h"
  26. #include "Sort.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
  147. allocator_ = AllocatorInitialize(sizeof(Node));
  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())->pair_.second_;
  212. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  213. Node* node = FindNode(key, hashKey);
  214. if (node)
  215. return node->pair_.second_;
  216. else
  217. return InsertNode(key, U())->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 = MakeHash(key) & (NumBuckets() - 1);
  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.
  262. Iterator Erase(const Iterator& it)
  263. {
  264. if (!ptrs_ || !it.ptr_)
  265. return End();
  266. Node* node = reinterpret_cast<Node*>(it.ptr_);
  267. Node* next = node->Next();
  268. unsigned hashKey = MakeHash(node->pair_.first_) & (NumBuckets() - 1);
  269. Node* previous = 0;
  270. Node* current = reinterpret_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. while (Size())
  288. EraseNode(Head());
  289. ResetPtrs();
  290. }
  291. /// Sort pairs. After sorting the map can be iterated in order until new elements are inserted.
  292. void Sort()
  293. {
  294. unsigned numKeys = Size();
  295. if (!numKeys)
  296. return;
  297. Node** ptrs = new Node*[numKeys];
  298. Node* ptr = Head();
  299. for (unsigned i = 0; i < numKeys; ++i)
  300. {
  301. ptrs[i] = ptr;
  302. ptr = ptr->Next();
  303. }
  304. Urho3D::Sort(RandomAccessIterator<Node*>(ptrs), RandomAccessIterator<Node*>(ptrs + numKeys), CompareNodes);
  305. for (unsigned i = 0; i < numKeys; ++i)
  306. {
  307. ptrs[i]->next_ = (i < numKeys - 1) ? ptrs[i + 1] : tail_;
  308. ptrs[i]->prev_ = (i > 0) ? ptrs[i - 1] : 0;
  309. }
  310. head_ = ptrs[0];
  311. tail_->prev_ = ptrs[numKeys - 1];
  312. delete[] ptrs;
  313. }
  314. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  315. bool Rehash(unsigned numBuckets)
  316. {
  317. if (numBuckets == NumBuckets())
  318. return true;
  319. if (!numBuckets || numBuckets < Size() / MAX_LOAD_FACTOR)
  320. return false;
  321. // Check for being power of two
  322. unsigned check = numBuckets;
  323. while (!(check & 1))
  324. check >>= 1;
  325. if (check != 1)
  326. return false;
  327. AllocateBuckets(Size(), numBuckets);
  328. Rehash();
  329. return true;
  330. }
  331. /// Return iterator to the pair with key, or end iterator if not found.
  332. Iterator Find(const T& key)
  333. {
  334. if (!ptrs_)
  335. return End();
  336. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  337. Node* node = FindNode(key, hashKey);
  338. if (node)
  339. return Iterator(node);
  340. else
  341. return End();
  342. }
  343. /// Return const iterator to the pair with key, or end iterator if not found.
  344. ConstIterator Find(const T& key) const
  345. {
  346. if (!ptrs_)
  347. return End();
  348. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  349. Node* node = FindNode(key, hashKey);
  350. if (node)
  351. return ConstIterator(node);
  352. else
  353. return End();
  354. }
  355. /// Return whether contains a pair with key.
  356. bool Contains(const T& key) const
  357. {
  358. if (!ptrs_)
  359. return false;
  360. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  361. return FindNode(key, hashKey) != 0;
  362. }
  363. /// Return iterator to the beginning.
  364. Iterator Begin() { return Iterator(Head()); }
  365. /// Return iterator to the beginning.
  366. ConstIterator Begin() const { return ConstIterator(Head()); }
  367. /// Return iterator to the end.
  368. Iterator End() { return Iterator(Tail()); }
  369. /// Return iterator to the end.
  370. ConstIterator End() const { return ConstIterator(Tail()); }
  371. /// Return first key.
  372. const T& Front() const { return *Begin(); }
  373. /// Return last key.
  374. const T& Back() const { return *(--End()); }
  375. private:
  376. /// Return the head node.
  377. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  378. /// Return the tail node.
  379. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  380. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  381. Node* FindNode(const T& key, unsigned hashKey) const
  382. {
  383. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  384. while (node)
  385. {
  386. if (node->pair_.first_ == key)
  387. return node;
  388. node = node->Down();
  389. }
  390. return 0;
  391. }
  392. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  393. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  394. {
  395. previous = 0;
  396. Node* node = reinterpret_cast<Node*>(Ptrs()[hashKey]);
  397. while (node)
  398. {
  399. if (node->pair_.first_ == key)
  400. return node;
  401. previous = node;
  402. node = node->Down();
  403. }
  404. return 0;
  405. }
  406. /// Insert a key and value and return either the new or existing node.
  407. Node* InsertNode(const T& key, const U& value)
  408. {
  409. // If no pointers yet, allocate with minimum bucket count
  410. if (!ptrs_)
  411. {
  412. AllocateBuckets(Size(), MIN_BUCKETS);
  413. Rehash();
  414. }
  415. unsigned hashKey = MakeHash(key) & (NumBuckets() - 1);
  416. // If exists, just change the value
  417. Node* existing = FindNode(key, hashKey);
  418. if (existing)
  419. {
  420. existing->pair_.second_ = value;
  421. return existing;
  422. }
  423. Node* newNode = InsertNode(Tail(), key, value);
  424. newNode->down_ = Ptrs()[hashKey];
  425. Ptrs()[hashKey] = newNode;
  426. // Rehash if the maximum load factor has been exceeded
  427. if (Size() > NumBuckets() * MAX_LOAD_FACTOR)
  428. {
  429. AllocateBuckets(Size(), NumBuckets() << 1);
  430. Rehash();
  431. }
  432. return newNode;
  433. }
  434. /// Insert a node into the list. Return the new node.
  435. Node* InsertNode(Node* dest, const T& key, const U& value)
  436. {
  437. if (!dest)
  438. return 0;
  439. Node* newNode = ReserveNode(key, value);
  440. Node* prev = dest->Prev();
  441. newNode->next_ = dest;
  442. newNode->prev_ = prev;
  443. if (prev)
  444. prev->next_ = newNode;
  445. dest->prev_ = newNode;
  446. // Reassign the head node if necessary
  447. if (dest == Head())
  448. head_ = newNode;
  449. SetSize(Size() + 1);
  450. return newNode;
  451. }
  452. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  453. Node* EraseNode(Node* node)
  454. {
  455. // The tail node can not be removed
  456. if (!node || node == tail_)
  457. return Tail();
  458. Node* prev = node->Prev();
  459. Node* next = node->Next();
  460. if (prev)
  461. prev->next_ = next;
  462. next->prev_ = prev;
  463. // Reassign the head node if necessary
  464. if (node == Head())
  465. head_ = next;
  466. FreeNode(node);
  467. SetSize(Size() - 1);
  468. return next;
  469. }
  470. /// Reserve a node.
  471. Node* ReserveNode()
  472. {
  473. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  474. new(newNode) Node();
  475. return newNode;
  476. }
  477. /// Reserve a node with specified key and value.
  478. Node* ReserveNode(const T& key, const U& value)
  479. {
  480. if (!allocator_)
  481. allocator_ = AllocatorInitialize(sizeof(Node));
  482. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  483. new(newNode) Node(key, value);
  484. return newNode;
  485. }
  486. /// Free a node.
  487. void FreeNode(Node* node)
  488. {
  489. (node)->~Node();
  490. AllocatorFree(allocator_, node);
  491. }
  492. /// Rehash the buckets.
  493. void Rehash()
  494. {
  495. for (Iterator i = Begin(); i != End(); ++i)
  496. {
  497. Node* node = reinterpret_cast<Node*>(i.ptr_);
  498. unsigned hashKey = MakeHash(i->first_) & (NumBuckets() - 1);
  499. node->down_ = Ptrs()[hashKey];
  500. Ptrs()[hashKey] = node;
  501. }
  502. }
  503. /// Compare two nodes.
  504. static bool CompareNodes(Node*& lhs, Node*& rhs) { return lhs->pair_.first_ < rhs->pair_.first_; }
  505. };
  506. }