HashMap.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  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. delete[] ptrs_;
  154. }
  155. /// Assign a hash map.
  156. HashMap& operator = (const HashMap<T, U>& rhs)
  157. {
  158. Clear();
  159. Insert(rhs);
  160. return *this;
  161. }
  162. /// Add-assign a pair.
  163. HashMap& operator += (const Pair<T, U>& rhs)
  164. {
  165. Insert(rhs);
  166. return *this;
  167. }
  168. /// Add-assign a hash map.
  169. HashMap& operator += (const HashMap<T, U>& rhs)
  170. {
  171. Insert(rhs);
  172. return *this;
  173. }
  174. /// Test for equality with another hash map. Warning: this is much slower than checking equality of two maps.
  175. bool operator == (const HashMap<T, U>& rhs) const
  176. {
  177. if (rhs.size_ != size_)
  178. return false;
  179. ConstIterator i = Begin();
  180. while (i != End())
  181. {
  182. ConstIterator j = rhs.Find(i->first_);
  183. if (j == rhs.End() || j->second_ != i->second_)
  184. return false;
  185. ++i;
  186. }
  187. return true;
  188. }
  189. /// Test for inequality with another hash map. Warning: this is much slower than checking inequality of two maps.
  190. bool operator != (const HashMap<T, U>& rhs) const
  191. {
  192. if (rhs.size_ != size_)
  193. return true;
  194. ConstIterator i = Begin();
  195. while (i != End())
  196. {
  197. ConstIterator j = rhs.Find(i->first_);
  198. if (j == rhs.End() || j->second_ != i->second_)
  199. return true;
  200. ++i;
  201. }
  202. return false;
  203. }
  204. /// Index the map. Create a new pair if key not found.
  205. U& operator [] (const T& key)
  206. {
  207. if (!numBuckets_)
  208. return InsertNode(key, U())->pair_.second_;
  209. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  210. Node* node = FindNode(key, hashKey);
  211. if (node)
  212. return node->pair_.second_;
  213. else
  214. return InsertNode(key, U())->pair_.second_;
  215. }
  216. /// Insert a pair. Return an iterator to it.
  217. Iterator Insert(const Pair<T, U>& pair)
  218. {
  219. return Iterator(InsertNode(pair.first_, pair.second_));
  220. }
  221. /// Insert a map.
  222. void Insert(const HashMap<T, U>& map)
  223. {
  224. ConstIterator it = map.Begin();
  225. ConstIterator end = map.End();
  226. while (it != end)
  227. {
  228. InsertNode(it->first_, it->second_);
  229. ++it;
  230. }
  231. }
  232. /// Insert a pair by iterator. Return iterator to the value.
  233. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
  234. /// Insert a range by iterators.
  235. void Insert(const ConstIterator& start, const ConstIterator& end)
  236. {
  237. ConstIterator it = start;
  238. while (it != end)
  239. InsertNode(*it++);
  240. }
  241. /// Erase a pair by key. Return true if was found.
  242. bool Erase(const T& key)
  243. {
  244. if (!numBuckets_)
  245. return false;
  246. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  247. Node* previous;
  248. Node* node = FindNode(key, hashKey, previous);
  249. if (!node)
  250. return false;
  251. if (previous)
  252. previous->down_ = node->down_;
  253. else
  254. ptrs_[hashKey] = node->down_;
  255. EraseNode(node);
  256. return true;
  257. }
  258. /// Erase a pair by iterator.
  259. void Erase(const Iterator& it) { Erase(it->first_); }
  260. /// Clear the map.
  261. void Clear()
  262. {
  263. while (size_)
  264. EraseNode(Head());
  265. // Reset bucket pointers
  266. for (unsigned i = 0; i < numBuckets_; ++i)
  267. ptrs_[i] = 0;
  268. }
  269. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  270. bool Rehash(unsigned numBuckets)
  271. {
  272. if (numBuckets == numBuckets_)
  273. return true;
  274. if (!numBuckets || numBuckets < size_ / MAX_LOAD_FACTOR)
  275. return false;
  276. // Check for being power of two
  277. unsigned check = numBuckets;
  278. while (!(check & 1))
  279. check >>= 1;
  280. if (check != 1)
  281. return false;
  282. numBuckets_ = numBuckets;
  283. Rehash();
  284. return true;
  285. }
  286. /// Return iterator to the pair with key, or end iterator if not found.
  287. Iterator Find(const T& key)
  288. {
  289. if (!numBuckets_)
  290. return End();
  291. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  292. Node* node = FindNode(key, hashKey);
  293. if (node)
  294. return Iterator(node);
  295. else
  296. return End();
  297. }
  298. /// Return const iterator to the pair with key, or end iterator if not found.
  299. ConstIterator Find(const T& key) const
  300. {
  301. if (!numBuckets_)
  302. return End();
  303. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  304. Node* node = FindNode(key, hashKey);
  305. if (node)
  306. return ConstIterator(node);
  307. else
  308. return End();
  309. }
  310. /// Return whether contains a pair with key.
  311. bool Contains(const T& key) const
  312. {
  313. if (!numBuckets_)
  314. return false;
  315. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  316. return FindNode(key, hashKey) != 0;
  317. }
  318. /// Return iterator to the beginning.
  319. Iterator Begin() { return Iterator(Head()); }
  320. /// Return iterator to the beginning.
  321. ConstIterator Begin() const { return ConstIterator(Head()); }
  322. /// Return iterator to the end.
  323. Iterator End() { return Iterator(Tail()); }
  324. /// Return iterator to the end.
  325. ConstIterator End() const { return ConstIterator(Tail()); }
  326. /// Return first key.
  327. const T& Front() const { return *Begin(); }
  328. /// Return last key.
  329. const T& Back() const { return *(--End()); }
  330. /// Return number of key-value pairs.
  331. unsigned Size() const { return size_; }
  332. /// Return whether map is empty.
  333. bool Empty() const { return size_ == 0; }
  334. private:
  335. /// Return the head node.
  336. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  337. /// Return the tail node.
  338. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  339. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  340. Node* FindNode(const T& key, unsigned hashKey) const
  341. {
  342. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  343. while (node)
  344. {
  345. if (node->pair_.first_ == key)
  346. return node;
  347. node = node->Down();
  348. }
  349. return 0;
  350. }
  351. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  352. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  353. {
  354. previous = 0;
  355. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  356. while (node)
  357. {
  358. if (node->pair_.first_ == key)
  359. return node;
  360. previous = node;
  361. node = node->Down();
  362. }
  363. return 0;
  364. }
  365. /// Insert a key and value and return either the new or existing node.
  366. Node* InsertNode(const T& key, const U& value)
  367. {
  368. // If no pointers yet, allocate with minimum bucket count
  369. if (!ptrs_)
  370. {
  371. numBuckets_ = MIN_BUCKETS;
  372. Rehash();
  373. }
  374. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  375. // If exists, just change the value
  376. Node* existing = FindNode(key, hashKey);
  377. if (existing)
  378. {
  379. existing->pair_.second_ = value;
  380. return existing;
  381. }
  382. Node* newNode = InsertNode(Tail(), key, value);
  383. newNode->down_ = ptrs_[hashKey];
  384. ptrs_[hashKey] = newNode;
  385. // Rehash if the maximum load factor has been exceeded
  386. if (size_ > numBuckets_ * MAX_LOAD_FACTOR)
  387. {
  388. numBuckets_ <<= 1;
  389. Rehash();
  390. }
  391. return newNode;
  392. }
  393. /// Insert a node into the list. Return the new node.
  394. Node* InsertNode(Node* dest, const T& key, const U& value)
  395. {
  396. if (!dest)
  397. return 0;
  398. Node* newNode = ReserveNode(key, value);
  399. Node* prev = dest->Prev();
  400. newNode->next_ = dest;
  401. newNode->prev_ = prev;
  402. if (prev)
  403. prev->next_ = newNode;
  404. dest->prev_ = newNode;
  405. // Reassign the head node if necessary
  406. if (dest == Head())
  407. head_ = newNode;
  408. ++size_;
  409. return newNode;
  410. }
  411. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  412. Node* EraseNode(Node* node)
  413. {
  414. // The tail node can not be removed
  415. if (!node || node == tail_)
  416. return Tail();
  417. Node* prev = node->Prev();
  418. Node* next = node->Next();
  419. if (prev)
  420. prev->next_ = next;
  421. next->prev_ = prev;
  422. // Reassign the head node if necessary
  423. if (node == Head())
  424. head_ = next;
  425. FreeNode(node);
  426. --size_;
  427. return next;
  428. }
  429. /// Reserve a node.
  430. Node* ReserveNode()
  431. {
  432. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  433. new(newNode) Node();
  434. return newNode;
  435. }
  436. /// Reserve a node with specified key and value.
  437. Node* ReserveNode(const T& key, const U& value)
  438. {
  439. if (!allocator_)
  440. allocator_ = AllocatorInitialize(sizeof(Node));
  441. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  442. new(newNode) Node(key, value);
  443. return newNode;
  444. }
  445. /// Free a node.
  446. void FreeNode(Node* node)
  447. {
  448. (node)->~Node();
  449. AllocatorFree(allocator_, node);
  450. }
  451. /// Reallocate and rehash the buckets.
  452. void Rehash()
  453. {
  454. delete[] ptrs_;
  455. ptrs_ = new HashNodeBase*[numBuckets_];
  456. for (unsigned i = 0; i < numBuckets_; ++i)
  457. ptrs_[i] = 0;
  458. for (Iterator i = Begin(); i != End(); ++i)
  459. {
  460. Node* node = reinterpret_cast<Node*>(i.ptr_);
  461. unsigned hashKey = MakeHash(i->first_) & (numBuckets_ - 1);
  462. node->down_ = ptrs_[hashKey];
  463. ptrs_[hashKey] = node;
  464. }
  465. }
  466. };