HashMap.h 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552
  1. //
  2. // Urho3D Engine
  3. // Copyright (c) 2008-2011 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. class Iterator : public HashIteratorBase
  77. {
  78. public:
  79. /// Construct.
  80. Iterator()
  81. {
  82. }
  83. /// Construct with a node pointer.
  84. Iterator(Node* ptr) :
  85. HashIteratorBase(ptr)
  86. {
  87. }
  88. /// Preincrement the pointer.
  89. Iterator& operator ++ () { GotoNext(); return *this; }
  90. /// Postincrement the pointer.
  91. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  92. /// Predecrement the pointer.
  93. Iterator& operator -- () { GotoPrev(); return *this; }
  94. /// Postdecrement the pointer.
  95. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  96. /// Point to the pair.
  97. KeyValue* operator -> () const { return &(static_cast<Node*>(ptr_))->pair_; }
  98. /// Dereference the pair.
  99. KeyValue& operator * () const { return (static_cast<Node*>(ptr_))->pair_; }
  100. };
  101. /// Hash map node const iterator.
  102. class ConstIterator : public HashIteratorBase
  103. {
  104. public:
  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. delete[] ptrs_;
  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. Warning: this is much slower than checking equality of two maps.
  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. Warning: this is much slower than checking inequality of two maps.
  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 (!numBuckets_)
  210. return InsertNode(key, U())->pair_.second_;
  211. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  212. Node* node = FindNode(key, hashKey);
  213. if (node)
  214. return node->pair_.second_;
  215. else
  216. return InsertNode(key, U())->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 (!numBuckets_)
  247. return false;
  248. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  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. void Erase(const Iterator& it) { Erase(it->first_); }
  262. /// Clear the map.
  263. void Clear()
  264. {
  265. while (size_)
  266. EraseNode(Head());
  267. // Reset bucket pointers
  268. for (unsigned i = 0; i < numBuckets_; ++i)
  269. ptrs_[i] = 0;
  270. }
  271. /// Rehash to a specific bucket count, which must be a power of two. Return true if successful.
  272. bool Rehash(unsigned numBuckets)
  273. {
  274. if (numBuckets == numBuckets_)
  275. return true;
  276. if (!numBuckets || numBuckets < size_ / MAX_LOAD_FACTOR)
  277. return false;
  278. // Check for being power of two
  279. unsigned check = numBuckets;
  280. while (!(check & 1))
  281. check >>= 1;
  282. if (check != 1)
  283. return false;
  284. numBuckets_ = numBuckets;
  285. Rehash();
  286. return true;
  287. }
  288. /// Return iterator to the pair with key, or end iterator if not found.
  289. Iterator Find(const T& key)
  290. {
  291. if (!numBuckets_)
  292. return End();
  293. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  294. Node* node = FindNode(key, hashKey);
  295. if (node)
  296. return Iterator(node);
  297. else
  298. return End();
  299. }
  300. /// Return const iterator to the pair with key, or end iterator if not found.
  301. ConstIterator Find(const T& key) const
  302. {
  303. if (!numBuckets_)
  304. return End();
  305. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  306. Node* node = FindNode(key, hashKey);
  307. if (node)
  308. return ConstIterator(node);
  309. else
  310. return End();
  311. }
  312. /// Return whether contains a pair with key.
  313. bool Contains(const T& key) const
  314. {
  315. if (!numBuckets_)
  316. return false;
  317. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  318. return FindNode(key, hashKey) != 0;
  319. }
  320. /// Return iterator to the beginning.
  321. Iterator Begin() { return Iterator(Head()); }
  322. /// Return iterator to the beginning.
  323. ConstIterator Begin() const { return ConstIterator(Head()); }
  324. /// Return iterator to the end.
  325. Iterator End() { return Iterator(Tail()); }
  326. /// Return iterator to the end.
  327. ConstIterator End() const { return ConstIterator(Tail()); }
  328. /// Return first key.
  329. const T& Front() const { return *Begin(); }
  330. /// Return last key.
  331. const T& Back() const { return *(--End()); }
  332. /// Return number of key-value pairs.
  333. unsigned Size() const { return size_; }
  334. /// Return whether map is empty.
  335. bool Empty() const { return size_ == 0; }
  336. private:
  337. /// Return the head pointer with correct type.
  338. Node* Head() const { return reinterpret_cast<Node*>(head_); }
  339. /// Return the tail pointer with correct type.
  340. Node* Tail() const { return reinterpret_cast<Node*>(tail_); }
  341. /// Find a node from the buckets. Do not call if the buckets have not been allocated.
  342. Node* FindNode(const T& key, unsigned hashKey) const
  343. {
  344. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  345. while (node)
  346. {
  347. if (node->pair_.first_ == key)
  348. return node;
  349. node = node->Down();
  350. }
  351. return 0;
  352. }
  353. /// Find a node and the previous node from the buckets. Do not call if the buckets have not been allocated.
  354. Node* FindNode(const T& key, unsigned hashKey, Node*& previous) const
  355. {
  356. previous = 0;
  357. Node* node = reinterpret_cast<Node*>(ptrs_[hashKey]);
  358. while (node)
  359. {
  360. if (node->pair_.first_ == key)
  361. return node;
  362. previous = node;
  363. node = node->Down();
  364. }
  365. return 0;
  366. }
  367. /// Insert a key and value and return either the new or existing node.
  368. Node* InsertNode(const T& key, const U& value)
  369. {
  370. // If no pointers yet, allocate with minimum bucket count
  371. if (!ptrs_)
  372. {
  373. numBuckets_ = MIN_BUCKETS;
  374. Rehash();
  375. }
  376. unsigned hashKey = MakeHash(key) & (numBuckets_ - 1);
  377. // If exists, just change the value
  378. Node* existing = FindNode(key, hashKey);
  379. if (existing)
  380. {
  381. existing->pair_.second_ = value;
  382. return existing;
  383. }
  384. Node* newNode = InsertNode(Tail(), key, value);
  385. newNode->down_ = ptrs_[hashKey];
  386. ptrs_[hashKey] = newNode;
  387. // Rehash if the maximum load factor has been exceeded
  388. if (size_ > numBuckets_ * MAX_LOAD_FACTOR)
  389. {
  390. numBuckets_ <<= 1;
  391. Rehash();
  392. }
  393. return newNode;
  394. }
  395. /// Insert a node into the list. Return the new node.
  396. Node* InsertNode(Node* dest, const T& key, const U& value)
  397. {
  398. if (!dest)
  399. return 0;
  400. Node* newNode = ReserveNode(key, value);
  401. Node* prev = dest->Prev();
  402. newNode->next_ = dest;
  403. newNode->prev_ = prev;
  404. if (prev)
  405. prev->next_ = newNode;
  406. dest->prev_ = newNode;
  407. // Reassign the head node if necessary
  408. if (dest == Head())
  409. head_ = newNode;
  410. ++size_;
  411. return newNode;
  412. }
  413. /// Erase a node from the list. Return pointer to the next element, or to the end if could not erase.
  414. Node* EraseNode(Node* toRemove)
  415. {
  416. // The tail node can not be removed
  417. if (!toRemove || toRemove == tail_)
  418. return Tail();
  419. Node* prev = toRemove->Prev();
  420. Node* next = toRemove->Next();
  421. if (prev)
  422. prev->next_ = next;
  423. next->prev_ = prev;
  424. // Reassign the head node if necessary
  425. if (toRemove == Head())
  426. head_ = next;
  427. FreeNode(toRemove);
  428. --size_;
  429. return next;
  430. }
  431. /// Reserve a node.
  432. Node* ReserveNode()
  433. {
  434. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  435. new(newNode) Node();
  436. return newNode;
  437. }
  438. /// Reserve a node with specified key and value.
  439. Node* ReserveNode(const T& key, const U& value)
  440. {
  441. if (!allocator_)
  442. allocator_ = AllocatorInitialize(sizeof(Node));
  443. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  444. new(newNode) Node(key, value);
  445. return newNode;
  446. }
  447. /// Free a node.
  448. void FreeNode(Node* node)
  449. {
  450. (node)->~Node();
  451. AllocatorFree(allocator_, node);
  452. }
  453. /// Reallocate and rehash the buckets.
  454. void Rehash()
  455. {
  456. delete[] ptrs_;
  457. ptrs_ = new HashNodeBase*[numBuckets_];
  458. for (unsigned i = 0; i < numBuckets_; ++i)
  459. ptrs_[i] = 0;
  460. for (Iterator i = Begin(); i != End(); ++i)
  461. {
  462. Node* node = reinterpret_cast<Node*>(i.ptr_);
  463. unsigned hashKey = MakeHash(i->first_) & (numBuckets_ - 1);
  464. node->down_ = ptrs_[hashKey];
  465. ptrs_[hashKey] = node;
  466. }
  467. }
  468. };