Map.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  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 "Pair.h"
  25. #include "TreeBase.h"
  26. // Based on Red Black Trees by Julienne Walker
  27. // http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_rbtree.aspx
  28. /// %Map template class using a red-black tree.
  29. template <class T, class U> class Map : public TreeBase
  30. {
  31. public:
  32. /// %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. /// %Map node.
  57. struct Node : public TreeNodeBase
  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 parent node.
  71. Node* Parent() const { return static_cast<Node*>(parent_); }
  72. /// Return the left or right child.
  73. Node* Child(unsigned dir) const { return static_cast<Node*>(link_[dir]); }
  74. };
  75. /// %Map iterator.
  76. struct Iterator : public TreeIteratorBase
  77. {
  78. /// Construct.
  79. Iterator()
  80. {
  81. }
  82. /// Construct with a node pointer.
  83. Iterator(Node* ptr) :
  84. TreeIteratorBase(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. /// %Map const iterator.
  101. struct ConstIterator : public TreeIteratorBase
  102. {
  103. /// Construct.
  104. ConstIterator()
  105. {
  106. }
  107. /// Construct with a node pointer.
  108. ConstIterator(Node* ptr) :
  109. TreeIteratorBase(ptr)
  110. {
  111. }
  112. /// Construct from a non-const iterator.
  113. ConstIterator(const Iterator& it) :
  114. TreeIteratorBase(it.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. Map()
  134. {
  135. }
  136. /// Construct from another map.
  137. Map(const Map<T, U>& map)
  138. {
  139. allocator_ = AllocatorInitialize(sizeof(Node), map.Size() + 1);
  140. *this = map;
  141. }
  142. /// Destruct.
  143. ~Map()
  144. {
  145. Clear();
  146. if (head_)
  147. {
  148. FreeNode(reinterpret_cast<Node*>(head_));
  149. head_ = 0;
  150. }
  151. AllocatorUninitialize(allocator_);
  152. }
  153. /// Assign a map.
  154. Map<T, U>& operator = (const Map<T, U>& rhs)
  155. {
  156. Clear();
  157. Insert(rhs);
  158. return *this;
  159. }
  160. /// Add-assign a value.
  161. Map& operator += (const Pair<T, U>& rhs)
  162. {
  163. Insert(rhs);
  164. return *this;
  165. }
  166. /// Add-assign a map.
  167. Map<T, U>& operator += (const Map<T, U>& rhs)
  168. {
  169. Insert(rhs);
  170. return *this;
  171. }
  172. /// Test for equality with another map.
  173. bool operator == (const Map<T, U>& rhs) const
  174. {
  175. if (rhs.size_ != size_)
  176. return false;
  177. ConstIterator i = Begin();
  178. ConstIterator j = rhs.Begin();
  179. while (i != End())
  180. {
  181. if (*i != *j)
  182. return false;
  183. ++i;
  184. ++j;
  185. }
  186. return true;
  187. }
  188. /// Test for inequality with another map.
  189. bool operator != (const Map<T, U>& rhs) const
  190. {
  191. if (rhs.size_ != size_)
  192. return true;
  193. ConstIterator i = Begin();
  194. ConstIterator j = rhs.Begin();
  195. while (i != End())
  196. {
  197. if (*i != *j)
  198. return true;
  199. ++i;
  200. ++j;
  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. Node* node = FindNode(key);
  208. if (node)
  209. return node->pair_.second_;
  210. else
  211. {
  212. node = InsertNode(key, U());
  213. return node->pair_.second_;
  214. }
  215. }
  216. /// Clear the map.
  217. void Clear()
  218. {
  219. Node* root = Root();
  220. if (!root)
  221. return;
  222. EraseNodes(root);
  223. head_->parent_ = 0;
  224. }
  225. /// Insert a pair and return iterator to it.
  226. Iterator Insert(const Pair<T, U>& pair) { return Iterator(InsertNode(pair.first_, pair.second_)); }
  227. /// Insert a map.
  228. void Insert(const Map<T, U>& map) { Insert(map.Begin(), map.End()); }
  229. /// Insert a pair by iterator. Return iterator to the value.
  230. Iterator Insert(const ConstIterator& it) { return Iterator(InsertNode(it->first_, it->second_)); }
  231. /// Insert a range by iterators.
  232. void Insert(const ConstIterator& start, const ConstIterator& end)
  233. {
  234. ConstIterator it = start;
  235. while (it != end)
  236. {
  237. InsertNode(it->first_, it->second_);
  238. ++it;
  239. }
  240. }
  241. /// Erase a pair by key. Return true if was found.
  242. bool Erase(const T& key) { return EraseNode(key); }
  243. /// Erase a pair by iterator.
  244. void Erase(const Iterator& it) { EraseNode(it->first_); }
  245. /// Erase a range by iterators.
  246. void Erase(const Iterator& start, const Iterator& end)
  247. {
  248. Iterator it = start;
  249. while (it != end)
  250. {
  251. Iterator current = it++;
  252. Erase(current);
  253. }
  254. }
  255. /// Return whether contains a pair with key.
  256. bool Contains(const T& key) const { return FindNode(key) != 0; }
  257. /// Return iterator to the pair, or end iterator if not found.
  258. Iterator Find(const T& key) { Node* node = FindNode(key); return node ? Iterator(node) : End(); }
  259. /// Return const iterator to the pair, or null iterator if not found.
  260. ConstIterator Find(const T& key) const { Node* node = FindNode(key); return node ? ConstIterator(node) : End(); }
  261. /// Return iterator to the beginning.
  262. Iterator Begin() { return Iterator(FindFirst()); }
  263. /// Return const iterator to the beginning.
  264. ConstIterator Begin() const { return ConstIterator(FindFirst()); }
  265. /// Return iterator to the end.
  266. Iterator End() { return ++Iterator(FindLast()); }
  267. /// Return const iterator to the end.
  268. ConstIterator End() const { return ++ConstIterator(FindLast()); }
  269. /// Return first key-value pair.
  270. KeyValue& Front() { return FindFirst()->pair_; }
  271. /// Return const first key-value pair.
  272. const KeyValue& Front() const { return FindFirst()->pair_; }
  273. /// Return last key-value pair.
  274. KeyValue& Back() { return FindLast()->pair_; }
  275. /// Return const last key-value pair.
  276. const KeyValue& Back() const { return FindLast()->pair_; }
  277. /// Return number of key-value pairs.
  278. unsigned Size() const { return size_; }
  279. /// Return whether map is empty.
  280. bool Empty() const { return size_ == 0; }
  281. private:
  282. /// Return the root node, or 0 if empty.
  283. Node* Root() const { return head_ ? reinterpret_cast<Node*>(head_->parent_) : 0; }
  284. /// Find the node with smallest key.
  285. Node* FindFirst() const
  286. {
  287. Node* node = Root();
  288. if (!node)
  289. return 0;
  290. // Search if not cached
  291. Node*& first = reinterpret_cast<Node*&>(head_->link_[0]);
  292. if (!first)
  293. {
  294. while (node && node->link_[0])
  295. node = node->Child(0);
  296. first = node;
  297. }
  298. return first;
  299. }
  300. /// Find the node with largest key.
  301. Node* FindLast() const
  302. {
  303. Node* node = Root();
  304. if (!node)
  305. return 0;
  306. // Search if not cached
  307. Node*& last = reinterpret_cast<Node*&>(head_->link_[1]);
  308. if (!last)
  309. {
  310. while (node && node->link_[1])
  311. node = node->Child(1);
  312. last = node;
  313. }
  314. return last;
  315. }
  316. /// Find a node with key. Return null if not found.
  317. Node* FindNode(const T& key) const
  318. {
  319. Node* node = Root();
  320. while (node)
  321. {
  322. if (node->pair_.first_ == key)
  323. return node;
  324. else
  325. node = node->Child(node->pair_.first_ < key);
  326. }
  327. return 0;
  328. }
  329. /// Insert a node and return pointer to it.
  330. Node* InsertNode(const T& key, const U& value)
  331. {
  332. Node* ret = 0;
  333. if (!allocator_)
  334. allocator_ = AllocatorInitialize(sizeof(Node));
  335. if (!head_)
  336. head_ = ReserveNode();
  337. if (!head_->parent_)
  338. {
  339. head_->parent_ = ret = ReserveNode(key, value);
  340. head_->link_[0] = head_->parent_;
  341. head_->link_[1] = head_->parent_;
  342. ++size_;
  343. }
  344. else
  345. {
  346. Node h;
  347. Node* g;
  348. Node* t;
  349. Node* p;
  350. Node* q;
  351. unsigned dir = 0;
  352. unsigned last = 0;
  353. t = &h;
  354. g = p = 0;
  355. q = reinterpret_cast<Node*>(head_->parent_);
  356. t->SetChild(1, q);
  357. for (;;)
  358. {
  359. if (!q)
  360. {
  361. p->SetChild(dir, q = ret = ReserveNode(key, value));
  362. ++size_;
  363. }
  364. else if (IsRed(q->link_[0]) && IsRed(q->link_[1]))
  365. {
  366. q->isRed_ = true;
  367. q->link_[0]->isRed_ = false;
  368. q->link_[1]->isRed_ = false;
  369. }
  370. if (IsRed(q) && IsRed(p))
  371. {
  372. unsigned dir2 = (t->link_[1] == g);
  373. if (q == p->link_[last])
  374. t->SetChild(dir2, RotateSingle(g, !last));
  375. else
  376. t->SetChild(dir2, RotateDouble(g, !last));
  377. }
  378. if (q->pair_.first_ == key)
  379. {
  380. ret = q;
  381. ret->pair_.second_ = value;
  382. break;
  383. }
  384. last = dir;
  385. dir = q->pair_.first_ < key;
  386. if (g)
  387. t = g;
  388. g = p;
  389. p = q;
  390. q = q->Child(dir);
  391. }
  392. head_->parent_ = h.Child(1);
  393. // Invalidate cached first and last nodes
  394. head_->link_[0] = 0;
  395. head_->link_[1] = 0;
  396. }
  397. head_->parent_->isRed_ = false;
  398. head_->parent_->parent_ = 0;
  399. return ret;
  400. }
  401. /// Erase a node. Return true if was erased.
  402. bool EraseNode(const T& key)
  403. {
  404. if (!head_ || !head_->parent_)
  405. return false;
  406. Node h;
  407. Node* q;
  408. Node* p;
  409. Node* g;
  410. Node* f;
  411. unsigned dir = 1;
  412. bool removed = false;
  413. q = &h;
  414. f = g = p = 0;
  415. q->SetChild(1, head_->parent_);
  416. while (q->link_[dir])
  417. {
  418. unsigned last = dir;
  419. g = p;
  420. p = q;
  421. q = q->Child(dir);
  422. dir = q->pair_.first_ < key;
  423. if (q->pair_.first_ == key)
  424. f = q;
  425. if (!IsRed(q) && !IsRed(q->link_[dir]))
  426. {
  427. if (IsRed(q->link_[!dir]))
  428. {
  429. p->SetChild(last, RotateSingle(q, dir));
  430. p = p->Child(last);
  431. }
  432. else if (!IsRed(q->link_[!dir]))
  433. {
  434. Node* s = p->Child(!last);
  435. if (s)
  436. {
  437. if (!IsRed(s->link_[!last]) && !IsRed(s->link_[last]))
  438. {
  439. p->isRed_ = false;
  440. s->isRed_ = true;
  441. q->isRed_ = true;
  442. }
  443. else
  444. {
  445. int dir2 = (g->link_[1] == p);
  446. if (IsRed(s->link_[last]))
  447. g->SetChild(dir2, RotateDouble(p, last));
  448. else if (IsRed(s->link_[!last]))
  449. g->SetChild(dir2, RotateSingle(p, last));
  450. Node* t = g->Child(dir2);
  451. q->isRed_ = t->isRed_ = true;
  452. t->link_[0]->isRed_ = false;
  453. t->link_[1]->isRed_ = false;
  454. }
  455. }
  456. }
  457. }
  458. }
  459. if (f)
  460. {
  461. const_cast<T&>(f->pair_.first_) = q->pair_.first_;
  462. f->pair_.second_ = q->pair_.second_;
  463. p->SetChild(p->Child(1) == q, q->link_[q->Child(0) == 0]);
  464. FreeNode(q);
  465. --size_;
  466. removed = true;
  467. }
  468. head_->parent_ = h.Child(1);
  469. if (head_->parent_)
  470. {
  471. head_->parent_->isRed_ = false;
  472. head_->parent_->parent_ = 0;
  473. }
  474. // Invalidate cached first and last nodes
  475. head_->link_[0] = 0;
  476. head_->link_[1] = 0;
  477. return removed;
  478. }
  479. /// Erase the nodes recursively.
  480. void EraseNodes(Node* node)
  481. {
  482. Node* left = node->Child(0);
  483. Node* right = node->Child(1);
  484. FreeNode(node);
  485. --size_;
  486. if (left)
  487. EraseNodes(left);
  488. if (right)
  489. EraseNodes(right);
  490. }
  491. /// Reserve a node.
  492. Node* ReserveNode()
  493. {
  494. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  495. new(newNode) Node();
  496. return newNode;
  497. }
  498. /// Reserve a node with specified key and value.
  499. Node* ReserveNode(const T& key, const U& value)
  500. {
  501. Node* newNode = static_cast<Node*>(AllocatorReserve(allocator_));
  502. new(newNode) Node(key, value);
  503. return newNode;
  504. }
  505. /// Free a node.
  506. void FreeNode(Node* node)
  507. {
  508. (node)->~Node();
  509. AllocatorFree(allocator_, node);
  510. }
  511. };