HashMap.h 16 KB

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