/AvalonEdit/ICSharpCode.AvalonEdit/Document/TextSegmentCollection.cs

http://github.com/icsharpcode/ILSpy · C# · 989 lines · 709 code · 91 blank · 189 comment · 263 complexity · f03f55d19241bdeca63af37e5d4e6e3f MD5 · raw file

  1. // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
  2. //
  3. // Permission is hereby granted, free of charge, to any person obtaining a copy of this
  4. // software and associated documentation files (the "Software"), to deal in the Software
  5. // without restriction, including without limitation the rights to use, copy, modify, merge,
  6. // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
  7. // to whom the Software is furnished to do so, subject to the following conditions:
  8. //
  9. // The above copyright notice and this permission notice shall be included in all copies or
  10. // substantial portions of the Software.
  11. //
  12. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
  13. // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
  14. // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
  15. // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  16. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
  17. // DEALINGS IN THE SOFTWARE.
  18. using System;
  19. using System.Collections.Generic;
  20. using System.Collections.ObjectModel;
  21. using System.Diagnostics;
  22. using System.Linq;
  23. using System.Text;
  24. using System.Windows;
  25. using ICSharpCode.AvalonEdit.Utils;
  26. #if NREFACTORY
  27. using ICSharpCode.NRefactory.Editor;
  28. #endif
  29. namespace ICSharpCode.AvalonEdit.Document
  30. {
  31. /// <summary>
  32. /// Interface to allow TextSegments to access the TextSegmentCollection - we cannot use a direct reference
  33. /// because TextSegmentCollection is generic.
  34. /// </summary>
  35. interface ISegmentTree
  36. {
  37. void Add(TextSegment s);
  38. void Remove(TextSegment s);
  39. void UpdateAugmentedData(TextSegment s);
  40. }
  41. /// <summary>
  42. /// <para>
  43. /// A collection of text segments that supports efficient lookup of segments
  44. /// intersecting with another segment.
  45. /// </para>
  46. /// </summary>
  47. /// <remarks><inheritdoc cref="TextSegment"/></remarks>
  48. /// <see cref="TextSegment"/>
  49. public sealed class TextSegmentCollection<T> : ICollection<T>, ISegmentTree, IWeakEventListener where T : TextSegment
  50. {
  51. // Implementation: this is basically a mixture of an augmented interval tree
  52. // and the TextAnchorTree.
  53. // WARNING: you need to understand interval trees (the version with the augmented 'high'/'max' field)
  54. // and how the TextAnchorTree works before you have any chance of understanding this code.
  55. // This means that every node holds two "segments":
  56. // one like the segments in the text anchor tree to support efficient offset changes
  57. // and another that is the interval as seen by the user
  58. // So basically, the tree contains a list of contiguous node segments of the first kind,
  59. // with interval segments starting at the end of every node segment.
  60. // Performance:
  61. // Add is O(lg n)
  62. // Remove is O(lg n)
  63. // DocumentChanged is O(m * lg n), with m the number of segments that intersect with the changed document section
  64. // FindFirstSegmentWithStartAfter is O(m + lg n) with m being the number of segments at the same offset as the result segment
  65. // FindIntersectingSegments is O(m + lg n) with m being the number of intersecting segments.
  66. int count;
  67. TextSegment root;
  68. bool isConnectedToDocument;
  69. #region Constructor
  70. /// <summary>
  71. /// Creates a new TextSegmentCollection that needs manual calls to <see cref="UpdateOffsets(DocumentChangeEventArgs)"/>.
  72. /// </summary>
  73. public TextSegmentCollection()
  74. {
  75. }
  76. /// <summary>
  77. /// Creates a new TextSegmentCollection that updates the offsets automatically.
  78. /// </summary>
  79. /// <param name="textDocument">The document to which the text segments
  80. /// that will be added to the tree belong. When the document changes, the
  81. /// position of the text segments will be updated accordingly.</param>
  82. public TextSegmentCollection(TextDocument textDocument)
  83. {
  84. if (textDocument == null)
  85. throw new ArgumentNullException("textDocument");
  86. textDocument.VerifyAccess();
  87. isConnectedToDocument = true;
  88. TextDocumentWeakEventManager.Changed.AddListener(textDocument, this);
  89. }
  90. #endregion
  91. #region OnDocumentChanged / UpdateOffsets
  92. bool IWeakEventListener.ReceiveWeakEvent(Type managerType, object sender, EventArgs e)
  93. {
  94. if (managerType == typeof(TextDocumentWeakEventManager.Changed)) {
  95. OnDocumentChanged((DocumentChangeEventArgs)e);
  96. return true;
  97. }
  98. return false;
  99. }
  100. /// <summary>
  101. /// Updates the start and end offsets of all segments stored in this collection.
  102. /// </summary>
  103. /// <param name="e">DocumentChangeEventArgs instance describing the change to the document.</param>
  104. public void UpdateOffsets(DocumentChangeEventArgs e)
  105. {
  106. if (e == null)
  107. throw new ArgumentNullException("e");
  108. if (isConnectedToDocument)
  109. throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
  110. OnDocumentChanged(e);
  111. CheckProperties();
  112. }
  113. void OnDocumentChanged(DocumentChangeEventArgs e)
  114. {
  115. OffsetChangeMap map = e.OffsetChangeMapOrNull;
  116. if (map != null) {
  117. foreach (OffsetChangeMapEntry entry in map) {
  118. UpdateOffsetsInternal(entry);
  119. }
  120. } else {
  121. UpdateOffsetsInternal(e.CreateSingleChangeMapEntry());
  122. }
  123. }
  124. /// <summary>
  125. /// Updates the start and end offsets of all segments stored in this collection.
  126. /// </summary>
  127. /// <param name="change">OffsetChangeMapEntry instance describing the change to the document.</param>
  128. public void UpdateOffsets(OffsetChangeMapEntry change)
  129. {
  130. if (isConnectedToDocument)
  131. throw new InvalidOperationException("This TextSegmentCollection will automatically update offsets; do not call UpdateOffsets manually!");
  132. UpdateOffsetsInternal(change);
  133. CheckProperties();
  134. }
  135. #endregion
  136. #region UpdateOffsets (implementation)
  137. void UpdateOffsetsInternal(OffsetChangeMapEntry change)
  138. {
  139. // Special case pure insertions, because they don't always cause a text segment to increase in size when the replaced region
  140. // is inside a segment (when offset is at start or end of a text semgent).
  141. if (change.RemovalLength == 0) {
  142. InsertText(change.Offset, change.InsertionLength);
  143. } else {
  144. ReplaceText(change);
  145. }
  146. }
  147. void InsertText(int offset, int length)
  148. {
  149. if (length == 0)
  150. return;
  151. // enlarge segments that contain offset (excluding those that have offset as endpoint)
  152. foreach (TextSegment segment in FindSegmentsContaining(offset)) {
  153. if (segment.StartOffset < offset && offset < segment.EndOffset) {
  154. segment.Length += length;
  155. }
  156. }
  157. // move start offsets of all segments >= offset
  158. TextSegment node = FindFirstSegmentWithStartAfter(offset);
  159. if (node != null) {
  160. node.nodeLength += length;
  161. UpdateAugmentedData(node);
  162. }
  163. }
  164. void ReplaceText(OffsetChangeMapEntry change)
  165. {
  166. Debug.Assert(change.RemovalLength > 0);
  167. int offset = change.Offset;
  168. foreach (TextSegment segment in FindOverlappingSegments(offset, change.RemovalLength)) {
  169. if (segment.StartOffset <= offset) {
  170. if (segment.EndOffset >= offset + change.RemovalLength) {
  171. // Replacement inside segment: adjust segment length
  172. segment.Length += change.InsertionLength - change.RemovalLength;
  173. } else {
  174. // Replacement starting inside segment and ending after segment end: set segment end to removal position
  175. //segment.EndOffset = offset;
  176. segment.Length = offset - segment.StartOffset;
  177. }
  178. } else {
  179. // Replacement starting in front of text segment and running into segment.
  180. // Keep segment.EndOffset constant and move segment.StartOffset to the end of the replacement
  181. int remainingLength = segment.EndOffset - (offset + change.RemovalLength);
  182. RemoveSegment(segment);
  183. segment.StartOffset = offset + change.RemovalLength;
  184. segment.Length = Math.Max(0, remainingLength);
  185. AddSegment(segment);
  186. }
  187. }
  188. // move start offsets of all segments > offset
  189. TextSegment node = FindFirstSegmentWithStartAfter(offset + 1);
  190. if (node != null) {
  191. Debug.Assert(node.nodeLength >= change.RemovalLength);
  192. node.nodeLength += change.InsertionLength - change.RemovalLength;
  193. UpdateAugmentedData(node);
  194. }
  195. }
  196. #endregion
  197. #region Add
  198. /// <summary>
  199. /// Adds the specified segment to the tree. This will cause the segment to update when the
  200. /// document changes.
  201. /// </summary>
  202. public void Add(T item)
  203. {
  204. if (item == null)
  205. throw new ArgumentNullException("item");
  206. if (item.ownerTree != null)
  207. throw new ArgumentException("The segment is already added to a SegmentCollection.");
  208. AddSegment(item);
  209. }
  210. void ISegmentTree.Add(TextSegment s)
  211. {
  212. AddSegment(s);
  213. }
  214. void AddSegment(TextSegment node)
  215. {
  216. int insertionOffset = node.StartOffset;
  217. node.distanceToMaxEnd = node.segmentLength;
  218. if (root == null) {
  219. root = node;
  220. node.totalNodeLength = node.nodeLength;
  221. } else if (insertionOffset >= root.totalNodeLength) {
  222. // append segment at end of tree
  223. node.nodeLength = node.totalNodeLength = insertionOffset - root.totalNodeLength;
  224. InsertAsRight(root.RightMost, node);
  225. } else {
  226. // insert in middle of tree
  227. TextSegment n = FindNode(ref insertionOffset);
  228. Debug.Assert(insertionOffset < n.nodeLength);
  229. // split node segment 'n' at offset
  230. node.totalNodeLength = node.nodeLength = insertionOffset;
  231. n.nodeLength -= insertionOffset;
  232. InsertBefore(n, node);
  233. }
  234. node.ownerTree = this;
  235. count++;
  236. CheckProperties();
  237. }
  238. void InsertBefore(TextSegment node, TextSegment newNode)
  239. {
  240. if (node.left == null) {
  241. InsertAsLeft(node, newNode);
  242. } else {
  243. InsertAsRight(node.left.RightMost, newNode);
  244. }
  245. }
  246. #endregion
  247. #region GetNextSegment / GetPreviousSegment
  248. /// <summary>
  249. /// Gets the next segment after the specified segment.
  250. /// Segments are sorted by their start offset.
  251. /// Returns null if segment is the last segment.
  252. /// </summary>
  253. public T GetNextSegment(T segment)
  254. {
  255. if (!Contains(segment))
  256. throw new ArgumentException("segment is not inside the segment tree");
  257. return (T)segment.Successor;
  258. }
  259. /// <summary>
  260. /// Gets the previous segment before the specified segment.
  261. /// Segments are sorted by their start offset.
  262. /// Returns null if segment is the first segment.
  263. /// </summary>
  264. public T GetPreviousSegment(T segment)
  265. {
  266. if (!Contains(segment))
  267. throw new ArgumentException("segment is not inside the segment tree");
  268. return (T)segment.Predecessor;
  269. }
  270. #endregion
  271. #region FirstSegment/LastSegment
  272. /// <summary>
  273. /// Returns the first segment in the collection or null, if the collection is empty.
  274. /// </summary>
  275. public T FirstSegment {
  276. get {
  277. return root == null ? null : (T)root.LeftMost;
  278. }
  279. }
  280. /// <summary>
  281. /// Returns the last segment in the collection or null, if the collection is empty.
  282. /// </summary>
  283. public T LastSegment {
  284. get {
  285. return root == null ? null : (T)root.RightMost;
  286. }
  287. }
  288. #endregion
  289. #region FindFirstSegmentWithStartAfter
  290. /// <summary>
  291. /// Gets the first segment with a start offset greater or equal to <paramref name="startOffset"/>.
  292. /// Returns null if no such segment is found.
  293. /// </summary>
  294. public T FindFirstSegmentWithStartAfter(int startOffset)
  295. {
  296. if (root == null)
  297. return null;
  298. if (startOffset <= 0)
  299. return (T)root.LeftMost;
  300. TextSegment s = FindNode(ref startOffset);
  301. // startOffset means that the previous segment is starting at the offset we were looking for
  302. while (startOffset == 0) {
  303. TextSegment p = (s == null) ? root.RightMost : s.Predecessor;
  304. // There must always be a predecessor: if we were looking for the first node, we would have already
  305. // returned it as root.LeftMost above.
  306. Debug.Assert(p != null);
  307. startOffset += p.nodeLength;
  308. s = p;
  309. }
  310. return (T)s;
  311. }
  312. /// <summary>
  313. /// Finds the node at the specified offset.
  314. /// After the method has run, offset is relative to the beginning of the returned node.
  315. /// </summary>
  316. TextSegment FindNode(ref int offset)
  317. {
  318. TextSegment n = root;
  319. while (true) {
  320. if (n.left != null) {
  321. if (offset < n.left.totalNodeLength) {
  322. n = n.left; // descend into left subtree
  323. continue;
  324. } else {
  325. offset -= n.left.totalNodeLength; // skip left subtree
  326. }
  327. }
  328. if (offset < n.nodeLength) {
  329. return n; // found correct node
  330. } else {
  331. offset -= n.nodeLength; // skip this node
  332. }
  333. if (n.right != null) {
  334. n = n.right; // descend into right subtree
  335. } else {
  336. // didn't find any node containing the offset
  337. return null;
  338. }
  339. }
  340. }
  341. #endregion
  342. #region FindOverlappingSegments
  343. /// <summary>
  344. /// Finds all segments that contain the given offset.
  345. /// (StartOffset &lt;= offset &lt;= EndOffset)
  346. /// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
  347. /// </summary>
  348. /// <returns>Returns a new collection containing the results of the query.
  349. /// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
  350. public ReadOnlyCollection<T> FindSegmentsContaining(int offset)
  351. {
  352. return FindOverlappingSegments(offset, 0);
  353. }
  354. /// <summary>
  355. /// Finds all segments that overlap with the given segment (including touching segments).
  356. /// </summary>
  357. /// <returns>Returns a new collection containing the results of the query.
  358. /// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
  359. public ReadOnlyCollection<T> FindOverlappingSegments(ISegment segment)
  360. {
  361. if (segment == null)
  362. throw new ArgumentNullException("segment");
  363. return FindOverlappingSegments(segment.Offset, segment.Length);
  364. }
  365. /// <summary>
  366. /// Finds all segments that overlap with the given segment (including touching segments).
  367. /// Segments are returned in the order given by GetNextSegment/GetPreviousSegment.
  368. /// </summary>
  369. /// <returns>Returns a new collection containing the results of the query.
  370. /// This means it is safe to modify the TextSegmentCollection while iterating through the result collection.</returns>
  371. public ReadOnlyCollection<T> FindOverlappingSegments(int offset, int length)
  372. {
  373. ThrowUtil.CheckNotNegative(length, "length");
  374. List<T> results = new List<T>();
  375. if (root != null) {
  376. FindOverlappingSegments(results, root, offset, offset + length);
  377. }
  378. return results.AsReadOnly();
  379. }
  380. void FindOverlappingSegments(List<T> results, TextSegment node, int low, int high)
  381. {
  382. // low and high are relative to node.LeftMost startpos (not node.LeftMost.Offset)
  383. if (high < 0) {
  384. // node is irrelevant for search because all intervals in node are after high
  385. return;
  386. }
  387. // find values relative to node.Offset
  388. int nodeLow = low - node.nodeLength;
  389. int nodeHigh = high - node.nodeLength;
  390. if (node.left != null) {
  391. nodeLow -= node.left.totalNodeLength;
  392. nodeHigh -= node.left.totalNodeLength;
  393. }
  394. if (node.distanceToMaxEnd < nodeLow) {
  395. // node is irrelevant for search because all intervals in node are before low
  396. return;
  397. }
  398. if (node.left != null)
  399. FindOverlappingSegments(results, node.left, low, high);
  400. if (nodeHigh < 0) {
  401. // node and everything in node.right is before low
  402. return;
  403. }
  404. if (nodeLow <= node.segmentLength) {
  405. results.Add((T)node);
  406. }
  407. if (node.right != null)
  408. FindOverlappingSegments(results, node.right, nodeLow, nodeHigh);
  409. }
  410. #endregion
  411. #region UpdateAugmentedData
  412. void UpdateAugmentedData(TextSegment node)
  413. {
  414. int totalLength = node.nodeLength;
  415. int distanceToMaxEnd = node.segmentLength;
  416. if (node.left != null) {
  417. totalLength += node.left.totalNodeLength;
  418. int leftDTME = node.left.distanceToMaxEnd;
  419. // dtme is relative, so convert it to the coordinates of node:
  420. if (node.left.right != null)
  421. leftDTME -= node.left.right.totalNodeLength;
  422. leftDTME -= node.nodeLength;
  423. if (leftDTME > distanceToMaxEnd)
  424. distanceToMaxEnd = leftDTME;
  425. }
  426. if (node.right != null) {
  427. totalLength += node.right.totalNodeLength;
  428. int rightDTME = node.right.distanceToMaxEnd;
  429. // dtme is relative, so convert it to the coordinates of node:
  430. rightDTME += node.right.nodeLength;
  431. if (node.right.left != null)
  432. rightDTME += node.right.left.totalNodeLength;
  433. if (rightDTME > distanceToMaxEnd)
  434. distanceToMaxEnd = rightDTME;
  435. }
  436. if (node.totalNodeLength != totalLength
  437. || node.distanceToMaxEnd != distanceToMaxEnd)
  438. {
  439. node.totalNodeLength = totalLength;
  440. node.distanceToMaxEnd = distanceToMaxEnd;
  441. if (node.parent != null)
  442. UpdateAugmentedData(node.parent);
  443. }
  444. }
  445. void ISegmentTree.UpdateAugmentedData(TextSegment node)
  446. {
  447. UpdateAugmentedData(node);
  448. }
  449. #endregion
  450. #region Remove
  451. /// <summary>
  452. /// Removes the specified segment from the tree. This will cause the segment to not update
  453. /// anymore when the document changes.
  454. /// </summary>
  455. public bool Remove(T item)
  456. {
  457. if (!Contains(item))
  458. return false;
  459. RemoveSegment(item);
  460. return true;
  461. }
  462. void ISegmentTree.Remove(TextSegment s)
  463. {
  464. RemoveSegment(s);
  465. }
  466. void RemoveSegment(TextSegment s)
  467. {
  468. int oldOffset = s.StartOffset;
  469. TextSegment successor = s.Successor;
  470. if (successor != null)
  471. successor.nodeLength += s.nodeLength;
  472. RemoveNode(s);
  473. if (successor != null)
  474. UpdateAugmentedData(successor);
  475. Disconnect(s, oldOffset);
  476. CheckProperties();
  477. }
  478. void Disconnect(TextSegment s, int offset)
  479. {
  480. s.left = s.right = s.parent = null;
  481. s.ownerTree = null;
  482. s.nodeLength = offset;
  483. count--;
  484. }
  485. /// <summary>
  486. /// Removes all segments from the tree.
  487. /// </summary>
  488. public void Clear()
  489. {
  490. T[] segments = this.ToArray();
  491. root = null;
  492. int offset = 0;
  493. foreach (TextSegment s in segments) {
  494. offset += s.nodeLength;
  495. Disconnect(s, offset);
  496. }
  497. CheckProperties();
  498. }
  499. #endregion
  500. #region CheckProperties
  501. [Conditional("DATACONSISTENCYTEST")]
  502. internal void CheckProperties()
  503. {
  504. #if DEBUG
  505. if (root != null) {
  506. CheckProperties(root);
  507. // check red-black property:
  508. int blackCount = -1;
  509. CheckNodeProperties(root, null, RED, 0, ref blackCount);
  510. }
  511. int expectedCount = 0;
  512. // we cannot trust LINQ not to call ICollection.Count, so we need this loop
  513. // to count the elements in the tree
  514. using (IEnumerator<T> en = GetEnumerator()) {
  515. while (en.MoveNext()) expectedCount++;
  516. }
  517. Debug.Assert(count == expectedCount);
  518. #endif
  519. }
  520. #if DEBUG
  521. void CheckProperties(TextSegment node)
  522. {
  523. int totalLength = node.nodeLength;
  524. int distanceToMaxEnd = node.segmentLength;
  525. if (node.left != null) {
  526. CheckProperties(node.left);
  527. totalLength += node.left.totalNodeLength;
  528. distanceToMaxEnd = Math.Max(distanceToMaxEnd,
  529. node.left.distanceToMaxEnd + node.left.StartOffset - node.StartOffset);
  530. }
  531. if (node.right != null) {
  532. CheckProperties(node.right);
  533. totalLength += node.right.totalNodeLength;
  534. distanceToMaxEnd = Math.Max(distanceToMaxEnd,
  535. node.right.distanceToMaxEnd + node.right.StartOffset - node.StartOffset);
  536. }
  537. Debug.Assert(node.totalNodeLength == totalLength);
  538. Debug.Assert(node.distanceToMaxEnd == distanceToMaxEnd);
  539. }
  540. /*
  541. 1. A node is either red or black.
  542. 2. The root is black.
  543. 3. All leaves are black. (The leaves are the NIL children.)
  544. 4. Both children of every red node are black. (So every red node must have a black parent.)
  545. 5. Every simple path from a node to a descendant leaf contains the same number of black nodes. (Not counting the leaf node.)
  546. */
  547. void CheckNodeProperties(TextSegment node, TextSegment parentNode, bool parentColor, int blackCount, ref int expectedBlackCount)
  548. {
  549. if (node == null) return;
  550. Debug.Assert(node.parent == parentNode);
  551. if (parentColor == RED) {
  552. Debug.Assert(node.color == BLACK);
  553. }
  554. if (node.color == BLACK) {
  555. blackCount++;
  556. }
  557. if (node.left == null && node.right == null) {
  558. // node is a leaf node:
  559. if (expectedBlackCount == -1)
  560. expectedBlackCount = blackCount;
  561. else
  562. Debug.Assert(expectedBlackCount == blackCount);
  563. }
  564. CheckNodeProperties(node.left, node, node.color, blackCount, ref expectedBlackCount);
  565. CheckNodeProperties(node.right, node, node.color, blackCount, ref expectedBlackCount);
  566. }
  567. static void AppendTreeToString(TextSegment node, StringBuilder b, int indent)
  568. {
  569. if (node.color == RED)
  570. b.Append("RED ");
  571. else
  572. b.Append("BLACK ");
  573. b.AppendLine(node.ToString() + node.ToDebugString());
  574. indent += 2;
  575. if (node.left != null) {
  576. b.Append(' ', indent);
  577. b.Append("L: ");
  578. AppendTreeToString(node.left, b, indent);
  579. }
  580. if (node.right != null) {
  581. b.Append(' ', indent);
  582. b.Append("R: ");
  583. AppendTreeToString(node.right, b, indent);
  584. }
  585. }
  586. #endif
  587. internal string GetTreeAsString()
  588. {
  589. #if DEBUG
  590. StringBuilder b = new StringBuilder();
  591. if (root != null)
  592. AppendTreeToString(root, b, 0);
  593. return b.ToString();
  594. #else
  595. return "Not available in release build.";
  596. #endif
  597. }
  598. #endregion
  599. #region Red/Black Tree
  600. internal const bool RED = true;
  601. internal const bool BLACK = false;
  602. void InsertAsLeft(TextSegment parentNode, TextSegment newNode)
  603. {
  604. Debug.Assert(parentNode.left == null);
  605. parentNode.left = newNode;
  606. newNode.parent = parentNode;
  607. newNode.color = RED;
  608. UpdateAugmentedData(parentNode);
  609. FixTreeOnInsert(newNode);
  610. }
  611. void InsertAsRight(TextSegment parentNode, TextSegment newNode)
  612. {
  613. Debug.Assert(parentNode.right == null);
  614. parentNode.right = newNode;
  615. newNode.parent = parentNode;
  616. newNode.color = RED;
  617. UpdateAugmentedData(parentNode);
  618. FixTreeOnInsert(newNode);
  619. }
  620. void FixTreeOnInsert(TextSegment node)
  621. {
  622. Debug.Assert(node != null);
  623. Debug.Assert(node.color == RED);
  624. Debug.Assert(node.left == null || node.left.color == BLACK);
  625. Debug.Assert(node.right == null || node.right.color == BLACK);
  626. TextSegment parentNode = node.parent;
  627. if (parentNode == null) {
  628. // we inserted in the root -> the node must be black
  629. // since this is a root node, making the node black increments the number of black nodes
  630. // on all paths by one, so it is still the same for all paths.
  631. node.color = BLACK;
  632. return;
  633. }
  634. if (parentNode.color == BLACK) {
  635. // if the parent node where we inserted was black, our red node is placed correctly.
  636. // since we inserted a red node, the number of black nodes on each path is unchanged
  637. // -> the tree is still balanced
  638. return;
  639. }
  640. // parentNode is red, so there is a conflict here!
  641. // because the root is black, parentNode is not the root -> there is a grandparent node
  642. TextSegment grandparentNode = parentNode.parent;
  643. TextSegment uncleNode = Sibling(parentNode);
  644. if (uncleNode != null && uncleNode.color == RED) {
  645. parentNode.color = BLACK;
  646. uncleNode.color = BLACK;
  647. grandparentNode.color = RED;
  648. FixTreeOnInsert(grandparentNode);
  649. return;
  650. }
  651. // now we know: parent is red but uncle is black
  652. // First rotation:
  653. if (node == parentNode.right && parentNode == grandparentNode.left) {
  654. RotateLeft(parentNode);
  655. node = node.left;
  656. } else if (node == parentNode.left && parentNode == grandparentNode.right) {
  657. RotateRight(parentNode);
  658. node = node.right;
  659. }
  660. // because node might have changed, reassign variables:
  661. parentNode = node.parent;
  662. grandparentNode = parentNode.parent;
  663. // Now recolor a bit:
  664. parentNode.color = BLACK;
  665. grandparentNode.color = RED;
  666. // Second rotation:
  667. if (node == parentNode.left && parentNode == grandparentNode.left) {
  668. RotateRight(grandparentNode);
  669. } else {
  670. // because of the first rotation, this is guaranteed:
  671. Debug.Assert(node == parentNode.right && parentNode == grandparentNode.right);
  672. RotateLeft(grandparentNode);
  673. }
  674. }
  675. void RemoveNode(TextSegment removedNode)
  676. {
  677. if (removedNode.left != null && removedNode.right != null) {
  678. // replace removedNode with it's in-order successor
  679. TextSegment leftMost = removedNode.right.LeftMost;
  680. RemoveNode(leftMost); // remove leftMost from its current location
  681. // and overwrite the removedNode with it
  682. ReplaceNode(removedNode, leftMost);
  683. leftMost.left = removedNode.left;
  684. if (leftMost.left != null) leftMost.left.parent = leftMost;
  685. leftMost.right = removedNode.right;
  686. if (leftMost.right != null) leftMost.right.parent = leftMost;
  687. leftMost.color = removedNode.color;
  688. UpdateAugmentedData(leftMost);
  689. if (leftMost.parent != null) UpdateAugmentedData(leftMost.parent);
  690. return;
  691. }
  692. // now either removedNode.left or removedNode.right is null
  693. // get the remaining child
  694. TextSegment parentNode = removedNode.parent;
  695. TextSegment childNode = removedNode.left ?? removedNode.right;
  696. ReplaceNode(removedNode, childNode);
  697. if (parentNode != null) UpdateAugmentedData(parentNode);
  698. if (removedNode.color == BLACK) {
  699. if (childNode != null && childNode.color == RED) {
  700. childNode.color = BLACK;
  701. } else {
  702. FixTreeOnDelete(childNode, parentNode);
  703. }
  704. }
  705. }
  706. void FixTreeOnDelete(TextSegment node, TextSegment parentNode)
  707. {
  708. Debug.Assert(node == null || node.parent == parentNode);
  709. if (parentNode == null)
  710. return;
  711. // warning: node may be null
  712. TextSegment sibling = Sibling(node, parentNode);
  713. if (sibling.color == RED) {
  714. parentNode.color = RED;
  715. sibling.color = BLACK;
  716. if (node == parentNode.left) {
  717. RotateLeft(parentNode);
  718. } else {
  719. RotateRight(parentNode);
  720. }
  721. sibling = Sibling(node, parentNode); // update value of sibling after rotation
  722. }
  723. if (parentNode.color == BLACK
  724. && sibling.color == BLACK
  725. && GetColor(sibling.left) == BLACK
  726. && GetColor(sibling.right) == BLACK)
  727. {
  728. sibling.color = RED;
  729. FixTreeOnDelete(parentNode, parentNode.parent);
  730. return;
  731. }
  732. if (parentNode.color == RED
  733. && sibling.color == BLACK
  734. && GetColor(sibling.left) == BLACK
  735. && GetColor(sibling.right) == BLACK)
  736. {
  737. sibling.color = RED;
  738. parentNode.color = BLACK;
  739. return;
  740. }
  741. if (node == parentNode.left &&
  742. sibling.color == BLACK &&
  743. GetColor(sibling.left) == RED &&
  744. GetColor(sibling.right) == BLACK)
  745. {
  746. sibling.color = RED;
  747. sibling.left.color = BLACK;
  748. RotateRight(sibling);
  749. }
  750. else if (node == parentNode.right &&
  751. sibling.color == BLACK &&
  752. GetColor(sibling.right) == RED &&
  753. GetColor(sibling.left) == BLACK)
  754. {
  755. sibling.color = RED;
  756. sibling.right.color = BLACK;
  757. RotateLeft(sibling);
  758. }
  759. sibling = Sibling(node, parentNode); // update value of sibling after rotation
  760. sibling.color = parentNode.color;
  761. parentNode.color = BLACK;
  762. if (node == parentNode.left) {
  763. if (sibling.right != null) {
  764. Debug.Assert(sibling.right.color == RED);
  765. sibling.right.color = BLACK;
  766. }
  767. RotateLeft(parentNode);
  768. } else {
  769. if (sibling.left != null) {
  770. Debug.Assert(sibling.left.color == RED);
  771. sibling.left.color = BLACK;
  772. }
  773. RotateRight(parentNode);
  774. }
  775. }
  776. void ReplaceNode(TextSegment replacedNode, TextSegment newNode)
  777. {
  778. if (replacedNode.parent == null) {
  779. Debug.Assert(replacedNode == root);
  780. root = newNode;
  781. } else {
  782. if (replacedNode.parent.left == replacedNode)
  783. replacedNode.parent.left = newNode;
  784. else
  785. replacedNode.parent.right = newNode;
  786. }
  787. if (newNode != null) {
  788. newNode.parent = replacedNode.parent;
  789. }
  790. replacedNode.parent = null;
  791. }
  792. void RotateLeft(TextSegment p)
  793. {
  794. // let q be p's right child
  795. TextSegment q = p.right;
  796. Debug.Assert(q != null);
  797. Debug.Assert(q.parent == p);
  798. // set q to be the new root
  799. ReplaceNode(p, q);
  800. // set p's right child to be q's left child
  801. p.right = q.left;
  802. if (p.right != null) p.right.parent = p;
  803. // set q's left child to be p
  804. q.left = p;
  805. p.parent = q;
  806. UpdateAugmentedData(p);
  807. UpdateAugmentedData(q);
  808. }
  809. void RotateRight(TextSegment p)
  810. {
  811. // let q be p's left child
  812. TextSegment q = p.left;
  813. Debug.Assert(q != null);
  814. Debug.Assert(q.parent == p);
  815. // set q to be the new root
  816. ReplaceNode(p, q);
  817. // set p's left child to be q's right child
  818. p.left = q.right;
  819. if (p.left != null) p.left.parent = p;
  820. // set q's right child to be p
  821. q.right = p;
  822. p.parent = q;
  823. UpdateAugmentedData(p);
  824. UpdateAugmentedData(q);
  825. }
  826. static TextSegment Sibling(TextSegment node)
  827. {
  828. if (node == node.parent.left)
  829. return node.parent.right;
  830. else
  831. return node.parent.left;
  832. }
  833. static TextSegment Sibling(TextSegment node, TextSegment parentNode)
  834. {
  835. Debug.Assert(node == null || node.parent == parentNode);
  836. if (node == parentNode.left)
  837. return parentNode.right;
  838. else
  839. return parentNode.left;
  840. }
  841. static bool GetColor(TextSegment node)
  842. {
  843. return node != null ? node.color : BLACK;
  844. }
  845. #endregion
  846. #region ICollection<T> implementation
  847. /// <summary>
  848. /// Gets the number of segments in the tree.
  849. /// </summary>
  850. public int Count {
  851. get { return count; }
  852. }
  853. bool ICollection<T>.IsReadOnly {
  854. get { return false; }
  855. }
  856. /// <summary>
  857. /// Gets whether this tree contains the specified item.
  858. /// </summary>
  859. public bool Contains(T item)
  860. {
  861. return item != null && item.ownerTree == this;
  862. }
  863. /// <summary>
  864. /// Copies all segments in this SegmentTree to the specified array.
  865. /// </summary>
  866. public void CopyTo(T[] array, int arrayIndex)
  867. {
  868. if (array == null)
  869. throw new ArgumentNullException("array");
  870. if (array.Length < this.Count)
  871. throw new ArgumentException("The array is too small", "array");
  872. if (arrayIndex < 0 || arrayIndex + count > array.Length)
  873. throw new ArgumentOutOfRangeException("arrayIndex", arrayIndex, "Value must be between 0 and " + (array.Length - count));
  874. foreach (T s in this) {
  875. array[arrayIndex++] = s;
  876. }
  877. }
  878. /// <summary>
  879. /// Gets an enumerator to enumerate the segments.
  880. /// </summary>
  881. public IEnumerator<T> GetEnumerator()
  882. {
  883. if (root != null) {
  884. TextSegment current = root.LeftMost;
  885. while (current != null) {
  886. yield return (T)current;
  887. // TODO: check if collection was modified during enumeration
  888. current = current.Successor;
  889. }
  890. }
  891. }
  892. System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
  893. {
  894. return this.GetEnumerator();
  895. }
  896. #endregion
  897. }
  898. }