Set.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  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 "ListBase.h"
  25. #include <new>
  26. // Based on http://eternallyconfuzzled.com/tuts/datastructures/jsw_tut_skip.aspx
  27. /// Set template class using a skip list
  28. template <class T> class Set : public SkipListBase
  29. {
  30. public:
  31. /// Set node
  32. struct Node : public SkipListNodeBase
  33. {
  34. /// Key
  35. T key_;
  36. /// Return next node on a specific height
  37. Node* GetNext(unsigned height) const
  38. {
  39. if (!height)
  40. return static_cast<Node*>(next_);
  41. else
  42. return static_cast<Node*>(levels_[height - 1]);
  43. }
  44. /// Return previous node
  45. Node* GetPrev() { return static_cast<Node*>(prev_); }
  46. };
  47. /// Set node iterator
  48. class Iterator : public ListIteratorBase
  49. {
  50. friend class ConstIterator;
  51. public:
  52. /// Construct
  53. explicit Iterator(Node* ptr) :
  54. ListIteratorBase(ptr)
  55. {
  56. }
  57. /// Preincrement the pointer
  58. Iterator& operator ++ () { GotoNext(); return *this; }
  59. /// Postincrement the pointer
  60. Iterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  61. /// Predecrement the pointer
  62. Iterator& operator -- () { GotoPrev(); return *this; }
  63. /// Postdecrement the pointer
  64. Iterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  65. /// Point to the key
  66. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  67. /// Dereference the key
  68. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  69. };
  70. /// Set node const iterator
  71. class ConstIterator : public ListIteratorBase
  72. {
  73. public:
  74. /// Construct
  75. explicit ConstIterator(Node* ptr) :
  76. ListIteratorBase(ptr)
  77. {
  78. }
  79. /// Construct from a non-const iterator
  80. ConstIterator(const Iterator& rhs) :
  81. ListIteratorBase(rhs.ptr_)
  82. {
  83. }
  84. /// Assign from a non-const iterator
  85. ConstIterator& operator = (const Iterator& rhs) { ptr_ = rhs.ptr_; return *this; }
  86. /// Preincrement the pointer
  87. ConstIterator& operator ++ () { GotoNext(); return *this; }
  88. /// Postincrement the pointer
  89. ConstIterator operator ++ (int) { Iterator it = *this; GotoNext(); return it; }
  90. /// Predecrement the pointer
  91. ConstIterator& operator -- () { GotoPrev(); return *this; }
  92. /// Postdecrement the pointer
  93. ConstIterator operator -- (int) { Iterator it = *this; GotoPrev(); return it; }
  94. /// Point to the key
  95. const T* operator -> () const { return &(static_cast<Node*>(ptr_))->key_; }
  96. /// Dereference the key
  97. const T& operator * () const { return (static_cast<Node*>(ptr_))->key_; }
  98. };
  99. /// Construct empty
  100. Set(unsigned maxHeight = MAX_HEIGHT) :
  101. SkipListBase(maxHeight)
  102. {
  103. // Allocate the head and tail nodes and zero the next pointers
  104. head_ = AllocateNode(maxHeight_);
  105. tail_ = AllocateNode(maxHeight_);
  106. Node* head = GetHead();
  107. Node* tail = GetTail();
  108. for (unsigned i = 0; i < maxHeight_; ++i)
  109. {
  110. head->SetNext(i, tail);
  111. tail->SetNext(i, 0);
  112. }
  113. // Allocate the fixup pointers
  114. fix_ = reinterpret_cast<void**>(new Node*[maxHeight_]);
  115. }
  116. /// Construct from another set
  117. Set(const Set<T>& set) :
  118. SkipListBase(set.maxHeight_)
  119. {
  120. // Allocate the head and tail nodes and zero the next pointers
  121. head_ = AllocateNode(maxHeight_);
  122. tail_ = AllocateNode(maxHeight_);
  123. Node* head = GetHead();
  124. Node* tail = GetTail();
  125. for (unsigned i = 0; i < maxHeight_; ++i)
  126. {
  127. head->SetNext(i, tail);
  128. tail->SetNext(i, 0);
  129. }
  130. // Allocate the fixup pointers
  131. fix_ = reinterpret_cast<void**>(new Node*[maxHeight_]);
  132. // Then assign the another set
  133. *this = set;
  134. }
  135. /// Destruct
  136. ~Set()
  137. {
  138. Clear();
  139. DeleteNode(GetHead());
  140. DeleteNode(GetTail());
  141. delete[] GetFix();
  142. }
  143. /// Assign from another set
  144. Set& operator = (const Set<T>& rhs)
  145. {
  146. Clear();
  147. // Insert the nodes with same heights
  148. for (Node* i = rhs.GetHead()->GetNext(0); i != rhs.GetTail(); i = i->GetNext(0))
  149. InsertNode(i->key_, i->height_);
  150. return *this;
  151. }
  152. /// Add-assign a key
  153. Set& operator += (const T& rhs)
  154. {
  155. Insert(rhs);
  156. return *this;
  157. }
  158. /// Add-assign a set
  159. Set& operator += (const Set<T>& rhs)
  160. {
  161. Insert(rhs.Begin(), rhs.End());
  162. return *this;
  163. }
  164. /// Test for equality with another set
  165. bool operator == (const Set<T>& rhs) const
  166. {
  167. if (rhs.size_ != size_)
  168. return false;
  169. ConstIterator i = Begin();
  170. ConstIterator j = rhs.Begin();
  171. while (i != End())
  172. {
  173. if (*i != *j)
  174. return false;
  175. ++i;
  176. ++j;
  177. }
  178. return true;
  179. }
  180. /// Test for inequality with another set
  181. bool operator != (const Set<T>& rhs) const
  182. {
  183. if (rhs.size_ != size_)
  184. return true;
  185. ConstIterator i = Begin();
  186. ConstIterator j = rhs.Begin();
  187. while (i != End())
  188. {
  189. if (*i != *j)
  190. return true;
  191. ++i;
  192. ++j;
  193. }
  194. return false;
  195. }
  196. /// Insert into the set. Return true if did not exist already
  197. bool Insert(const T& key)
  198. {
  199. return InsertNode(key, 0);
  200. }
  201. /// Insert a range by iterators
  202. void Insert(const Iterator& start, const Iterator& end)
  203. {
  204. Iterator it = start;
  205. while ((it) && (it != end))
  206. {
  207. Iterator current = it++;
  208. Insert(*current);
  209. // Break if the iterator got stuck
  210. if (it == current)
  211. break;
  212. }
  213. }
  214. /// Erase a key from the set. Return true if was found and erased
  215. bool Erase(const T& key)
  216. {
  217. Node* head = GetHead();
  218. Node* tail = GetTail();
  219. Node** fix = GetFix();
  220. Node* i = head;
  221. for (unsigned j = height_ - 1; j < MAX_HEIGHT; --j)
  222. {
  223. for (;;)
  224. {
  225. Node* next = i->GetNext(j);
  226. if ((next) && (next != tail) && (key > next->key_))
  227. i = next;
  228. else
  229. break;
  230. }
  231. fix[j] = i;
  232. }
  233. // Check if key does not exist
  234. Node* toRemove = i->GetNext(0);
  235. if ((!toRemove) || (toRemove == tail) || (toRemove->key_ != key))
  236. return false;
  237. // Fix the previous link. However, do not set the head node as a previous link
  238. Node* prev = toRemove->GetPrev();
  239. Node* next = toRemove->GetNext(0);
  240. if (next)
  241. next->SetPrev(prev != head ? prev : 0);
  242. // Fix the next links
  243. for (unsigned j = 0; j < height_; ++j)
  244. {
  245. Node* fixNext = fix[j]->GetNext(j);
  246. if (fixNext)
  247. fix[j]->SetNext(j, fixNext->GetNext(j));
  248. }
  249. // Check if height should be changed
  250. while (height_ > 0)
  251. {
  252. if (head->GetNext(height_ - 1))
  253. break;
  254. head->SetNext(--height_, 0);
  255. }
  256. DeleteNode(toRemove);
  257. --size_;
  258. return true;
  259. }
  260. /// Erase by an iterator. Return an iterator to the next element
  261. Iterator Erase(Iterator it)
  262. {
  263. if (it != End())
  264. {
  265. Iterator current = it++;
  266. Erase(*current);
  267. }
  268. return it;
  269. }
  270. /// Erase by a range of iterators. Return the end iterator
  271. Iterator Erase(const Iterator& start, const Iterator& end)
  272. {
  273. Iterator it = start;
  274. while (it != end)
  275. {
  276. Iterator current = it++;
  277. // Break if the iterator got stuck
  278. if (it == current)
  279. break;
  280. Erase(*current);
  281. }
  282. return it;
  283. }
  284. /// Clear the set
  285. void Clear()
  286. {
  287. // Let the head and tails node remain, but reset the next pointers
  288. Node* head = GetHead();
  289. Node* tail = GetTail();
  290. Node* node = head->GetNext(0);
  291. for (unsigned i = 0; i < maxHeight_; ++i)
  292. {
  293. head->SetNext(i, tail);
  294. tail->SetPrev(0);
  295. }
  296. // Then remove all the key nodes
  297. while (node != tail)
  298. {
  299. Node* current = node;
  300. node = node->GetNext(0);
  301. DeleteNode(current);
  302. }
  303. height_ = 0;
  304. size_ = 0;
  305. }
  306. /// Return iterator to the node with key, or end iterator if not found
  307. Iterator Find(const T& key) { Node* node = FindNode(key); return node ? Iterator(node) : End(); }
  308. /// Return const iterator to the node with key, or null iterator if not found
  309. ConstIterator Find(const T& key) const { Node* node = FindNode(key); return node ? ConstIterator(node) : End(); }
  310. /// Return iterator to the first actual node
  311. Iterator Begin() { return Iterator(GetHead()->GetNext(0)); }
  312. /// Return iterator to the first actual node
  313. ConstIterator Begin() const { return ConstIterator(GetHead()->GetNext(0)); }
  314. /// Return iterator to the end
  315. Iterator End() { return Iterator(GetTail()); }
  316. /// Return iterator to the end
  317. ConstIterator End() const { return ConstIterator(GetTail()); }
  318. /// Return first key
  319. const T& Front() const { return *Begin(); }
  320. /// Return last key
  321. const T& Back() const { return *(--End()); }
  322. /// Return whether contains a key
  323. bool Contains(const T& key) const { return FindNode(key) != 0; }
  324. /// Return number of keys
  325. unsigned Size() const { return size_; }
  326. /// Return current height
  327. unsigned Height() const { return height_; }
  328. /// Return whether set is empty
  329. bool Empty() const { return size_ == 0; }
  330. private:
  331. /// Return the head pointer with correct type
  332. Node* GetHead() const { return reinterpret_cast<Node*>(head_); }
  333. /// Return the tail pointer with correct type
  334. Node* GetTail() const { return reinterpret_cast<Node*>(tail_); }
  335. /// Return the fixup array with correct type
  336. Node** GetFix() const { return reinterpret_cast<Node**>(fix_); }
  337. /// Find a key from the set. Return null if not found
  338. Node* FindNode(const T& key) const
  339. {
  340. Node* i = GetHead();
  341. Node* tail = GetTail();
  342. for (unsigned j = height_ - 1; j < MAX_HEIGHT; --j)
  343. {
  344. for (;;)
  345. {
  346. Node* next = i->GetNext(j);
  347. if ((next) && (next != tail) && (key > next->key_))
  348. i = next;
  349. else
  350. break;
  351. }
  352. }
  353. Node* next = i->GetNext(0);
  354. if ((next) && (next != tail) && (next->key_ == key))
  355. return next;
  356. else
  357. return 0;
  358. }
  359. /// Insert into the set with a specific height. Zero height will randomize
  360. bool InsertNode(const T& key, unsigned height)
  361. {
  362. Node* head = GetHead();
  363. Node* tail = GetTail();
  364. Node** fix = GetFix();
  365. Node* i = head;
  366. for (unsigned j = height_ - 1; j < MAX_HEIGHT; --j)
  367. {
  368. for (;;)
  369. {
  370. Node* next = i->GetNext(j);
  371. if ((next) && (next != tail) && (key > next->key_))
  372. i = next;
  373. else
  374. break;
  375. }
  376. fix[j] = i;
  377. }
  378. // Check if key already exists
  379. Node* next = i->GetNext(0);
  380. if ((next) && (next != tail) && (next->key_ == key))
  381. return false;
  382. // Create new node, assign height and key
  383. if (!height)
  384. height = GetHeight();
  385. Node* newNode = AllocateNode(height);
  386. newNode->key_ = key;
  387. // Fix the previous link, however do not set the head node as previous
  388. if (i != head)
  389. newNode->SetPrev(i);
  390. if (next)
  391. next->SetPrev(newNode);
  392. while (newNode->height_ > height_)
  393. fix[height_++] = head;
  394. for (unsigned h = 0; h < newNode->height_; ++h)
  395. {
  396. newNode->SetNext(h, fix[h]->GetNext(h));
  397. fix[h]->SetNext(h, newNode);
  398. }
  399. ++size_;
  400. return true;
  401. }
  402. /// Allocate a node and its next pointers
  403. Node* AllocateNode(unsigned height)
  404. {
  405. unsigned char* block = new unsigned char[sizeof(Node) + (height - 1) * sizeof(Node*)];
  406. Node* newNode = reinterpret_cast<Node*>(block);
  407. // Construct the key with placement new and set the next pointers' address
  408. new(&newNode->key_) T();
  409. newNode->height_ = height;
  410. if (height > 1)
  411. newNode->levels_ = reinterpret_cast<SkipListNodeBase**>(block + sizeof(Node));
  412. else
  413. newNode->levels_ = 0;
  414. return newNode;
  415. }
  416. /// Delete a node
  417. void DeleteNode(Node* node)
  418. {
  419. // Destruct the key, then delete the memory block
  420. (&node->key_)->~T();
  421. delete[] reinterpret_cast<unsigned char*>(node);
  422. }
  423. };