Mirror of Svelto.ECS because we're a fan of it
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

628 lines
20KB

  1. // Uncomment this to enable the following debugging aids:
  2. // LeftLeaningRedBlackTree.HtmlFragment
  3. // LeftLeaningRedBlackTree.EntityView.HtmlFragment
  4. // LeftLeaningRedBlackTree.AssertInvariants
  5. // #define DEBUGGING
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Diagnostics;
  9. /// <summary>
  10. /// Implements a left-leaning red-black tree.
  11. /// </summary>
  12. /// <remarks>
  13. /// Based on the research paper "Left-leaning Red-Black Trees"
  14. /// by Robert Sedgewick. More information available at:
  15. /// http://www.cs.princeton.edu/~rs/talks/LLRB/RedBlack.pdf
  16. /// http://www.cs.princeton.edu/~rs/talks/LLRB/08Penn.pdf
  17. /// </remarks>
  18. /// <typeparam name="TKey">Type of keys.</typeparam>
  19. public class LeftLeaningKeyedRedBlackTree<TKey> where TKey: IComparable<TKey>
  20. {
  21. /// <summary>
  22. /// Stores the root entityView of the tree.
  23. /// </summary>
  24. private EntityView _rootEntityView;
  25. /// <summary>
  26. /// Represents a entityView of the tree.
  27. /// </summary>
  28. /// <remarks>
  29. /// Using fields instead of properties drops execution time by about 40%.
  30. /// </remarks>
  31. [DebuggerDisplay("Key={Key}")]
  32. private class EntityView
  33. {
  34. /// <summary>
  35. /// Gets or sets the entityView's key.
  36. /// </summary>
  37. public TKey Key;
  38. /// <summary>
  39. /// Gets or sets the left entityView.
  40. /// </summary>
  41. public EntityView Left;
  42. /// <summary>
  43. /// Gets or sets the right entityView.
  44. /// </summary>
  45. public EntityView Right;
  46. /// <summary>
  47. /// Gets or sets the color of the entityView.
  48. /// </summary>
  49. public bool IsBlack;
  50. #if DEBUGGING
  51. /// <summary>
  52. /// Gets an HTML fragment representing the entityView and its children.
  53. /// </summary>
  54. public string HtmlFragment
  55. {
  56. get
  57. {
  58. return
  59. "<table border='1'>" +
  60. "<tr>" +
  61. "<td colspan='2' align='center' bgcolor='" + (IsBlack ? "gray" : "red") + "'>" + Key + ", " + Value + " [" + Siblings + "]</td>" +
  62. "</tr>" +
  63. "<tr>" +
  64. "<td valign='top'>" + (null != Left ? Left.HtmlFragment : "[null]") + "</td>" +
  65. "<td valign='top'>" + (null != Right ? Right.HtmlFragment : "[null]") + "</td>" +
  66. "</tr>" +
  67. "</table>";
  68. }
  69. }
  70. #endif
  71. }
  72. /// <summary>
  73. /// Adds a key/value pair to the tree.
  74. /// </summary>
  75. /// <param name="key">Key to add.</param>
  76. public void Add(TKey key)
  77. {
  78. _rootEntityView = Add(_rootEntityView, key);
  79. _rootEntityView.IsBlack = true;
  80. #if DEBUGGING
  81. AssertInvariants();
  82. #endif
  83. }
  84. /// <summary>
  85. /// Removes a key/value pair from the tree.
  86. /// </summary>
  87. /// <param name="key">Key to remove.</param>
  88. /// <returns>True if key/value present and removed.</returns>
  89. public bool Remove(TKey key)
  90. {
  91. int initialCount = Count;
  92. if (null != _rootEntityView)
  93. {
  94. _rootEntityView = Remove(_rootEntityView, key);
  95. if (null != _rootEntityView)
  96. {
  97. _rootEntityView.IsBlack = true;
  98. }
  99. }
  100. #if DEBUGGING
  101. AssertInvariants();
  102. #endif
  103. return initialCount != Count;
  104. }
  105. /// <summary>
  106. /// Removes all entityViews in the tree.
  107. /// </summary>
  108. public void Clear()
  109. {
  110. _rootEntityView = null;
  111. Count = 0;
  112. #if DEBUGGING
  113. AssertInvariants();
  114. #endif
  115. }
  116. /// <summary>
  117. /// Gets a sorted list of keys in the tree.
  118. /// </summary>
  119. /// <returns>Sorted list of keys.</returns>
  120. public IEnumerable<TKey> GetKeys()
  121. {
  122. TKey lastKey = default(TKey);
  123. bool lastKeyValid = false;
  124. return Traverse(
  125. _rootEntityView,
  126. n => !lastKeyValid || !object.Equals(lastKey, n.Key),
  127. n =>
  128. {
  129. lastKey = n.Key;
  130. lastKeyValid = true;
  131. return lastKey;
  132. });
  133. }
  134. /// <summary>
  135. /// Gets the count of key/value pairs in the tree.
  136. /// </summary>
  137. public int Count { get; private set; }
  138. /// <summary>
  139. /// Gets the minimum key in the tree.
  140. /// </summary>
  141. public TKey MinimumKey
  142. {
  143. get { return GetExtreme(_rootEntityView, n => n.Left, n => n.Key); }
  144. }
  145. /// <summary>
  146. /// Gets the maximum key in the tree.
  147. /// </summary>
  148. public TKey MaximumKey
  149. {
  150. get { return GetExtreme(_rootEntityView, n => n.Right, n => n.Key); }
  151. }
  152. /// <summary>
  153. /// Returns true if the specified entityView is red.
  154. /// </summary>
  155. /// <param name="entityView">Specified entityView.</param>
  156. /// <returns>True if specified entityView is red.</returns>
  157. private static bool IsRed(EntityView entityView)
  158. {
  159. if (null == entityView)
  160. {
  161. // "Virtual" leaf entityViews are always black
  162. return false;
  163. }
  164. return !entityView.IsBlack;
  165. }
  166. /// <summary>
  167. /// Adds the specified key/value pair below the specified root entityView.
  168. /// </summary>
  169. /// <param name="entityView">Specified entityView.</param>
  170. /// <param name="key">Key to add.</param>
  171. /// <param name="value">Value to add.</param>
  172. /// <returns>New root entityView.</returns>
  173. private EntityView Add(EntityView entityView, TKey key)
  174. {
  175. if (null == entityView)
  176. {
  177. // Insert new entityView
  178. Count++;
  179. return new EntityView { Key = key };
  180. }
  181. if (IsRed(entityView.Left) && IsRed(entityView.Right))
  182. {
  183. // Split entityView with two red children
  184. FlipColor(entityView);
  185. }
  186. // Find right place for new entityView
  187. int comparisonResult = KeyComparison(key, entityView.Key);
  188. if (comparisonResult < 0)
  189. {
  190. entityView.Left = Add(entityView.Left, key);
  191. }
  192. else if (0 < comparisonResult)
  193. {
  194. entityView.Right = Add(entityView.Right, key);
  195. }
  196. if (IsRed(entityView.Right))
  197. {
  198. // Rotate to prevent red entityView on right
  199. entityView = RotateLeft(entityView);
  200. }
  201. if (IsRed(entityView.Left) && IsRed(entityView.Left.Left))
  202. {
  203. // Rotate to prevent consecutive red entityViews
  204. entityView = RotateRight(entityView);
  205. }
  206. return entityView;
  207. }
  208. /// <summary>
  209. /// Removes the specified key/value pair from below the specified entityView.
  210. /// </summary>
  211. /// <param name="entityView">Specified entityView.</param>
  212. /// <param name="key">Key to remove.</param>
  213. /// <returns>True if key/value present and removed.</returns>
  214. private EntityView Remove(EntityView entityView, TKey key)
  215. {
  216. int comparisonResult = KeyComparison(key, entityView.Key);
  217. if (comparisonResult < 0)
  218. {
  219. // * Continue search if left is present
  220. if (null != entityView.Left)
  221. {
  222. if (!IsRed(entityView.Left) && !IsRed(entityView.Left.Left))
  223. {
  224. // Move a red entityView over
  225. entityView = MoveRedLeft(entityView);
  226. }
  227. // Remove from left
  228. entityView.Left = Remove(entityView.Left, key);
  229. }
  230. }
  231. else
  232. {
  233. if (IsRed(entityView.Left))
  234. {
  235. // Flip a 3 entityView or unbalance a 4 entityView
  236. entityView = RotateRight(entityView);
  237. }
  238. if ((0 == KeyComparison(key, entityView.Key)) && (null == entityView.Right))
  239. {
  240. // Remove leaf entityView
  241. Debug.Assert(null == entityView.Left, "About to remove an extra entityView.");
  242. Count--;
  243. // Leaf entityView is gone
  244. return null;
  245. }
  246. // * Continue search if right is present
  247. if (null != entityView.Right)
  248. {
  249. if (!IsRed(entityView.Right) && !IsRed(entityView.Right.Left))
  250. {
  251. // Move a red entityView over
  252. entityView = MoveRedRight(entityView);
  253. }
  254. if (0 == KeyComparison(key, entityView.Key))
  255. {
  256. // Remove leaf entityView
  257. Count--;
  258. // Find the smallest entityView on the right, swap, and remove it
  259. EntityView m = GetExtreme(entityView.Right, n => n.Left, n => n);
  260. entityView.Key = m.Key;
  261. entityView.Right = DeleteMinimum(entityView.Right);
  262. }
  263. else
  264. {
  265. // Remove from right
  266. entityView.Right = Remove(entityView.Right, key);
  267. }
  268. }
  269. }
  270. // Maintain invariants
  271. return FixUp(entityView);
  272. }
  273. /// <summary>
  274. /// Flip the colors of the specified entityView and its direct children.
  275. /// </summary>
  276. /// <param name="entityView">Specified entityView.</param>
  277. private static void FlipColor(EntityView entityView)
  278. {
  279. entityView.IsBlack = !entityView.IsBlack;
  280. entityView.Left.IsBlack = !entityView.Left.IsBlack;
  281. entityView.Right.IsBlack = !entityView.Right.IsBlack;
  282. }
  283. /// <summary>
  284. /// Rotate the specified entityView "left".
  285. /// </summary>
  286. /// <param name="entityView">Specified entityView.</param>
  287. /// <returns>New root entityView.</returns>
  288. private static EntityView RotateLeft(EntityView entityView)
  289. {
  290. EntityView x = entityView.Right;
  291. entityView.Right = x.Left;
  292. x.Left = entityView;
  293. x.IsBlack = entityView.IsBlack;
  294. entityView.IsBlack = false;
  295. return x;
  296. }
  297. /// <summary>
  298. /// Rotate the specified entityView "right".
  299. /// </summary>
  300. /// <param name="entityView">Specified entityView.</param>
  301. /// <returns>New root entityView.</returns>
  302. private static EntityView RotateRight(EntityView entityView)
  303. {
  304. EntityView x = entityView.Left;
  305. entityView.Left = x.Right;
  306. x.Right = entityView;
  307. x.IsBlack = entityView.IsBlack;
  308. entityView.IsBlack = false;
  309. return x;
  310. }
  311. /// <summary>
  312. /// Moves a red entityView from the right child to the left child.
  313. /// </summary>
  314. /// <param name="entityView">Parent entityView.</param>
  315. /// <returns>New root entityView.</returns>
  316. private static EntityView MoveRedLeft(EntityView entityView)
  317. {
  318. FlipColor(entityView);
  319. if (IsRed(entityView.Right.Left))
  320. {
  321. entityView.Right = RotateRight(entityView.Right);
  322. entityView = RotateLeft(entityView);
  323. FlipColor(entityView);
  324. // * Avoid creating right-leaning entityViews
  325. if (IsRed(entityView.Right.Right))
  326. {
  327. entityView.Right = RotateLeft(entityView.Right);
  328. }
  329. }
  330. return entityView;
  331. }
  332. /// <summary>
  333. /// Moves a red entityView from the left child to the right child.
  334. /// </summary>
  335. /// <param name="entityView">Parent entityView.</param>
  336. /// <returns>New root entityView.</returns>
  337. private static EntityView MoveRedRight(EntityView entityView)
  338. {
  339. FlipColor(entityView);
  340. if (IsRed(entityView.Left.Left))
  341. {
  342. entityView = RotateRight(entityView);
  343. FlipColor(entityView);
  344. }
  345. return entityView;
  346. }
  347. /// <summary>
  348. /// Deletes the minimum entityView under the specified entityView.
  349. /// </summary>
  350. /// <param name="entityView">Specified entityView.</param>
  351. /// <returns>New root entityView.</returns>
  352. private EntityView DeleteMinimum(EntityView entityView)
  353. {
  354. if (null == entityView.Left)
  355. {
  356. // Nothing to do
  357. return null;
  358. }
  359. if (!IsRed(entityView.Left) && !IsRed(entityView.Left.Left))
  360. {
  361. // Move red entityView left
  362. entityView = MoveRedLeft(entityView);
  363. }
  364. // Recursively delete
  365. entityView.Left = DeleteMinimum(entityView.Left);
  366. // Maintain invariants
  367. return FixUp(entityView);
  368. }
  369. /// <summary>
  370. /// Maintains invariants by adjusting the specified entityViews children.
  371. /// </summary>
  372. /// <param name="entityView">Specified entityView.</param>
  373. /// <returns>New root entityView.</returns>
  374. private static EntityView FixUp(EntityView entityView)
  375. {
  376. if (IsRed(entityView.Right))
  377. {
  378. // Avoid right-leaning entityView
  379. entityView = RotateLeft(entityView);
  380. }
  381. if (IsRed(entityView.Left) && IsRed(entityView.Left.Left))
  382. {
  383. // Balance 4-entityView
  384. entityView = RotateRight(entityView);
  385. }
  386. if (IsRed(entityView.Left) && IsRed(entityView.Right))
  387. {
  388. // Push red up
  389. FlipColor(entityView);
  390. }
  391. // * Avoid leaving behind right-leaning entityViews
  392. if ((null != entityView.Left) && IsRed(entityView.Left.Right) && !IsRed(entityView.Left.Left))
  393. {
  394. entityView.Left = RotateLeft(entityView.Left);
  395. if (IsRed(entityView.Left))
  396. {
  397. // Balance 4-entityView
  398. entityView = RotateRight(entityView);
  399. }
  400. }
  401. return entityView;
  402. }
  403. /// <summary>
  404. /// Gets the (first) entityView corresponding to the specified key.
  405. /// </summary>
  406. /// <param name="key">Key to search for.</param>
  407. /// <returns>Corresponding entityView or null if none found.</returns>
  408. private EntityView GetEntityViewForKey(TKey key)
  409. {
  410. // Initialize
  411. EntityView entityView = _rootEntityView;
  412. while (null != entityView)
  413. {
  414. // Compare keys and go left/right
  415. int comparisonResult = key.CompareTo(entityView.Key);
  416. if (comparisonResult < 0)
  417. {
  418. entityView = entityView.Left;
  419. }
  420. else if (0 < comparisonResult)
  421. {
  422. entityView = entityView.Right;
  423. }
  424. else
  425. {
  426. // Match; return entityView
  427. return entityView;
  428. }
  429. }
  430. // No match found
  431. return null;
  432. }
  433. /// <summary>
  434. /// Gets an extreme (ex: minimum/maximum) value.
  435. /// </summary>
  436. /// <typeparam name="T">Type of value.</typeparam>
  437. /// <param name="entityView">EntityView to start from.</param>
  438. /// <param name="successor">Successor function.</param>
  439. /// <param name="selector">Selector function.</param>
  440. /// <returns>Extreme value.</returns>
  441. private static T GetExtreme<T>(EntityView entityView, Func<EntityView, EntityView> successor, Func<EntityView, T> selector)
  442. {
  443. // Initialize
  444. T extreme = default(T);
  445. EntityView current = entityView;
  446. while (null != current)
  447. {
  448. // Go to extreme
  449. extreme = selector(current);
  450. current = successor(current);
  451. }
  452. return extreme;
  453. }
  454. /// <summary>
  455. /// Traverses a subset of the sequence of entityViews in order and selects the specified entityViews.
  456. /// </summary>
  457. /// <typeparam name="T">Type of elements.</typeparam>
  458. /// <param name="entityView">Starting entityView.</param>
  459. /// <param name="condition">Condition method.</param>
  460. /// <param name="selector">Selector method.</param>
  461. /// <returns>Sequence of selected entityViews.</returns>
  462. private IEnumerable<T> Traverse<T>(EntityView entityView, Func<EntityView, bool> condition, Func<EntityView, T> selector)
  463. {
  464. // Create a stack to avoid recursion
  465. Stack<EntityView> stack = new Stack<EntityView>();
  466. EntityView current = entityView;
  467. while (null != current)
  468. {
  469. if (null != current.Left)
  470. {
  471. // Save current state and go left
  472. stack.Push(current);
  473. current = current.Left;
  474. }
  475. else
  476. {
  477. do
  478. {
  479. // Select current entityView if relevant
  480. if (condition(current))
  481. {
  482. yield return selector(current);
  483. }
  484. // Go right - or up if nothing to the right
  485. current = current.Right;
  486. }
  487. while ((null == current) &&
  488. (0 < stack.Count) &&
  489. (null != (current = stack.Pop())));
  490. }
  491. }
  492. }
  493. /// <summary>
  494. /// Compares the specified keys (primary) and values (secondary).
  495. /// </summary>
  496. /// <param name="leftKey">The left key.</param>
  497. /// <param name="rightKey">The right key.</param>
  498. /// <returns>CompareTo-style results: -1 if left is less, 0 if equal, and 1 if greater than right.</returns>
  499. private int KeyComparison(TKey leftKey, TKey rightKey)
  500. {
  501. return leftKey.CompareTo(rightKey);
  502. }
  503. #if DEBUGGING
  504. /// <summary>
  505. /// Asserts that tree invariants are not violated.
  506. /// </summary>
  507. private void AssertInvariants()
  508. {
  509. // Root is black
  510. Debug.Assert((null == _rootEntityView) || _rootEntityView.IsBlack, "Root is not black");
  511. // Every path contains the same number of black entityViews
  512. Dictionary<EntityView, EntityView> parents = new Dictionary<LeftLeaningRedBlackTree<TKey, TValue>.EntityView, LeftLeaningRedBlackTree<TKey, TValue>.EntityView>();
  513. foreach (EntityView entityView in Traverse(_rootEntityView, n => true, n => n))
  514. {
  515. if (null != entityView.Left)
  516. {
  517. parents[entityView.Left] = entityView;
  518. }
  519. if (null != entityView.Right)
  520. {
  521. parents[entityView.Right] = entityView;
  522. }
  523. }
  524. if (null != _rootEntityView)
  525. {
  526. parents[_rootEntityView] = null;
  527. }
  528. int treeCount = -1;
  529. foreach (EntityView entityView in Traverse(_rootEntityView, n => (null == n.Left) || (null == n.Right), n => n))
  530. {
  531. int pathCount = 0;
  532. EntityView current = entityView;
  533. while (null != current)
  534. {
  535. if (current.IsBlack)
  536. {
  537. pathCount++;
  538. }
  539. current = parents[current];
  540. }
  541. Debug.Assert((-1 == treeCount) || (pathCount == treeCount), "Not all paths have the same number of black entityViews.");
  542. treeCount = pathCount;
  543. }
  544. // Verify entityView properties...
  545. foreach (EntityView entityView in Traverse(_rootEntityView, n => true, n => n))
  546. {
  547. // Left entityView is less
  548. if (null != entityView.Left)
  549. {
  550. Debug.Assert(0 > KeyAndValueComparison(entityView.Left.Key, entityView.Left.Value, entityView.Key, entityView.Value), "Left entityView is greater than its parent.");
  551. }
  552. // Right entityView is greater
  553. if (null != entityView.Right)
  554. {
  555. Debug.Assert(0 < KeyAndValueComparison(entityView.Right.Key, entityView.Right.Value, entityView.Key, entityView.Value), "Right entityView is less than its parent.");
  556. }
  557. // Both children of a red entityView are black
  558. Debug.Assert(!IsRed(entityView) || (!IsRed(entityView.Left) && !IsRed(entityView.Right)), "Red entityView has a red child.");
  559. // Always left-leaning
  560. Debug.Assert(!IsRed(entityView.Right) || IsRed(entityView.Left), "EntityView is not left-leaning.");
  561. // No consecutive reds (subset of previous rule)
  562. //Debug.Assert(!(IsRed(entityView) && IsRed(entityView.Left)));
  563. }
  564. }
  565. /// <summary>
  566. /// Gets an HTML fragment representing the tree.
  567. /// </summary>
  568. public string HtmlDocument
  569. {
  570. get
  571. {
  572. return
  573. "<html>" +
  574. "<body>" +
  575. (null != _rootEntityView ? _rootEntityView.HtmlFragment : "[null]") +
  576. "</body>" +
  577. "</html>";
  578. }
  579. }
  580. #endif
  581. }