Set.h 15 KB

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