Map.h 18 KB

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