|
| 1 | +using System.Collections; |
| 2 | +using System.Collections.Generic; |
| 3 | +using System.Diagnostics; |
| 4 | + |
| 5 | +namespace SourceGit.Models |
| 6 | +{ |
| 7 | + public class InlineElementCollector : IEnumerable<InlineElement> |
| 8 | + { |
| 9 | + private readonly List<InlineElement> _implementation = []; |
| 10 | + |
| 11 | + public void Clear() |
| 12 | + { |
| 13 | + _implementation.Clear(); |
| 14 | + |
| 15 | + AssertInvariant(); |
| 16 | + } |
| 17 | + |
| 18 | + public int Count => _implementation.Count; |
| 19 | + |
| 20 | + public void Add(InlineElement element) |
| 21 | + { |
| 22 | + |
| 23 | + var index = FindIndex(element.Start); |
| 24 | + if (!IsIntersection(index, element.Start, element.Length)) |
| 25 | + _implementation.Insert(index, element); |
| 26 | + |
| 27 | + AssertInvariant(); |
| 28 | + } |
| 29 | + |
| 30 | + [Conditional("DEBUG")] |
| 31 | + private void AssertInvariant() |
| 32 | + { |
| 33 | + if (_implementation.Count == 0) |
| 34 | + return; |
| 35 | + |
| 36 | + for (var index = 1; index < _implementation.Count; index++) |
| 37 | + { |
| 38 | + var prev = _implementation[index - 1]; |
| 39 | + var curr = _implementation[index]; |
| 40 | + |
| 41 | + Debug.Assert(prev.Start + prev.Length <= curr.Start); |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + public InlineElement Lookup(int position) |
| 46 | + { |
| 47 | + var index = FindIndex(position); |
| 48 | + return IsIntersection(index, position, 1) |
| 49 | + ? _implementation[index] |
| 50 | + : null; |
| 51 | + } |
| 52 | + |
| 53 | + private int FindIndex(int start) |
| 54 | + { |
| 55 | + var index = 0; |
| 56 | + while (index < _implementation.Count && _implementation[index].Start <= start) |
| 57 | + index++; |
| 58 | + |
| 59 | + return index; |
| 60 | + } |
| 61 | + |
| 62 | + private bool IsIntersection(int index, int start, int length) |
| 63 | + { |
| 64 | + if (index > 0) |
| 65 | + { |
| 66 | + var predecessor = _implementation[index - 1]; |
| 67 | + if (predecessor.Start + predecessor.Length >= start) |
| 68 | + return true; |
| 69 | + } |
| 70 | + |
| 71 | + if (index < _implementation.Count) |
| 72 | + { |
| 73 | + var successor = _implementation[index]; |
| 74 | + if (start + length >= successor.Start) |
| 75 | + return true; |
| 76 | + } |
| 77 | + |
| 78 | + return false; |
| 79 | + } |
| 80 | + |
| 81 | + public IEnumerator<InlineElement> GetEnumerator() => _implementation.GetEnumerator(); |
| 82 | + |
| 83 | + IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); |
| 84 | + } |
| 85 | +} |
0 commit comments