HashMap.h 16 KB

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