HashMap.h 15 KB

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