diff --git a/CHANGELOG.md b/CHANGELOG.md index 681c698..5450114 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,9 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ### Added +- `MarkupText.Create(string, ReadOnlySpan)`: text and its runs in one step, normalised as every + text's runs are, for a reader that already knows where each style starts and ends. Refuses overlapping + runs, a run without a set, and a point off its carrier, as `Wrap` does. - `UrlPolicy.RefusingControlCharacters()`: the same policy, also refusing a link address that holds a control character (U+0000–U+001F, U+007F–U+009F) or starts or ends with a space. A browser removes those before reading the scheme, so an MXP or Pueblo `href="java script:alert(1)"` passes `UrlPolicy.Safe` as a @@ -50,7 +53,9 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). runs in an array of exactly the right size: a third less allocated and a third faster for an 8-run line. - `Concat` and `Join` build their runs in an array of exactly the right size, and plain text builds none: concatenating two short plain texts allocates 96 B instead of 152 B. -- `AnsiEscapeParser.Parse` finds escapes with a vectorised search and reuses the shared palette colours. +- `AnsiEscapeParser.Parse` builds the text and its runs in one pass through `MarkupText.Create`, finds + escapes with a vectorised search, and reuses the markup of the last four styles it read: 2,000 characters + of coloured text parse in 12 µs and 6.4 KB instead of 32 µs and 44 KB. ### Fixed diff --git a/MarkupString.Ansi/AnsiEscapeParser.cs b/MarkupString.Ansi/AnsiEscapeParser.cs index 89a0691..9565f60 100644 --- a/MarkupString.Ansi/AnsiEscapeParser.cs +++ b/MarkupString.Ansi/AnsiEscapeParser.cs @@ -1,3 +1,4 @@ +using System.Buffers; namespace MarkupString.Ansi; /// @@ -22,33 +23,81 @@ public static MarkupText Parse(string? text) var first = text.IndexOf(Escape); if (first < 0) return MarkupText.Plain(text); - var segments = new List(); - var style = AnsiStyle.None; - // The layer the last styled segment was wrapped in: a style that comes back unchanged (a sequence - // that changed nothing, or one undone and redone) reuses it rather than building another. - AnsiMarkup? markup = null; - var position = first; - var segmentStart = 0; + // The text without its sequences, and a run for each styled stretch of it, built as they are read: + // one string and one run array, rather than a piece of text for every stretch joined at the end. + var chars = ArrayPool.Shared.Rent(text.Length); + var runs = ArrayPool.Shared.Rent(8); + var written = 0; + var runCount = 0; + try + { + var style = AnsiStyle.None; + // The sets the last few styles were given: text that switches between a handful of colours reuses + // them rather than building a layer for every stretch. + var recent = new RecentSets(); + var position = first; + var segmentStart = 0; + + while (true) + { + var end = position < 0 ? text.Length : position; + if (end > segmentStart) + { + text.AsSpan(segmentStart, end - segmentStart).CopyTo(chars.AsSpan(written)); + if (!style.IsNone) + { + var set = recent.For(style); + if (runCount == runs.Length) + { + var grown = ArrayPool.Shared.Rent(runs.Length * 2); + runs.AsSpan(0, runCount).CopyTo(grown); + ArrayPool.Shared.Return(runs, clearArray: true); + runs = grown; + } + runs[runCount++] = new Run(written, end - segmentStart, set); + } + written += end - segmentStart; + } + if (position < 0) break; + + position += ReadEscapeSequence(text, position, ref style); + segmentStart = position; + var next = position < text.Length ? text.AsSpan(position).IndexOf(Escape) : -1; + position = next < 0 ? -1 : position + next; + } - while (position >= 0) + return MarkupText.Create(new string(chars, 0, written), runs.AsSpan(0, runCount)); + } + finally { - if (position > segmentStart) segments.Add(Segment(text[segmentStart..position], style, ref markup)); - position += ReadEscapeSequence(text, position, ref style); - segmentStart = position; - var next = position < text.Length ? text.AsSpan(position).IndexOf(Escape) : -1; - position = next < 0 ? -1 : position + next; + ArrayPool.Shared.Return(chars); + ArrayPool.Shared.Return(runs, clearArray: true); } - - if (segmentStart < text.Length) segments.Add(Segment(text[segmentStart..], style, ref markup)); - - return MarkupText.Concat(segments); } - private static MarkupText Segment(string text, in AnsiStyle style, ref AnsiMarkup? markup) + /// The markup sets of the last four styles read, the oldest replaced first. + private struct RecentSets { - if (style.IsNone) return MarkupText.Plain(text); - if (markup is null || !markup.Style.Equals(style)) markup = new AnsiMarkup(style); - return MarkupText.Wrap(markup, text); + private Entries _entries; + private int _next; + + [System.Runtime.CompilerServices.InlineArray(4)] + private struct Entries + { + private (AnsiStyle Style, MarkupSet? Set) _entry; + } + + public MarkupSet For(in AnsiStyle style) + { + foreach (ref var entry in _entries) + if (entry.Set is not null && entry.Style.Equals(style)) + return entry.Set; + + var set = MarkupSet.Of(new AnsiMarkup(style)); + _entries[_next] = (style, set); + _next = (_next + 1) % 4; + return set; + } } /// Applies the sequence starting at and returns its length. diff --git a/MarkupString.Tests/Ansi/AnsiEscapeParserTests.cs b/MarkupString.Tests/Ansi/AnsiEscapeParserTests.cs index 8269b03..c78fcb0 100644 --- a/MarkupString.Tests/Ansi/AnsiEscapeParserTests.cs +++ b/MarkupString.Tests/Ansi/AnsiEscapeParserTests.cs @@ -240,4 +240,41 @@ public async Task UnterminatedCsi_ConsumesTheRest() { await Assert.That(AnsiEscapeParser.Parse($"abc{E}[31").Text).IsEqualTo("abc"); } + + /// + /// The text and its runs are built in one pass. A style that changes nothing between two stretches, or + /// comes back after plain text, still reads as the stretches it styles, sharing one set. + /// + [Test] + public async Task RepeatedStyle_SharesOneSetAndMergesWhereTheStretchesTouch() + { + var result = AnsiEscapeParser.Parse($"{E}[31mred{E}[31m more{E}[0m plain {E}[31mred again{E}[0m"); + + await Assert.That(result.Text).IsEqualTo("red more plain red again"); + await Assert.That(result.Runs.Length).IsEqualTo(2); + await Assert.That(result.Runs[0]).IsEqualTo(new Run(0, 8, result.Runs[0].Markups)); + await Assert.That(result.Runs[1].Start).IsEqualTo(15); + await Assert.That(result.Runs[1].Length).IsEqualTo(9); + await Assert.That(result.Runs[1].Markups).IsSameReferenceAs(result.Runs[0].Markups); + } + + /// Text of nothing but sequences is empty. + [Test] + public async Task OnlySequences_IsEmpty() + { + await Assert.That(AnsiEscapeParser.Parse($"{E}[31m{E}[0m{E}[2J")).IsSameReferenceAs(MarkupText.Empty); + } + + /// More styled stretches than the run buffer starts with. + [Test] + public async Task ManyStretches_KeepEveryRun() + { + var source = string.Concat(Enumerable.Range(0, 100).Select(i => $"{E}[3{i % 2 + 1}mx")); + var result = AnsiEscapeParser.Parse(source); + + await Assert.That(result.Text).IsEqualTo(new string('x', 100)); + await Assert.That(result.Runs.Length).IsEqualTo(100); + for (var i = 0; i < 100; i++) + await Assert.That(StyleOf(result, i).Foreground).IsEqualTo(new AnsiColor.Standard((byte)(i % 2 + 1), false)); + } } diff --git a/MarkupString.Tests/MarkupTextTests.cs b/MarkupString.Tests/MarkupTextTests.cs index 9cafcae..380d352 100644 --- a/MarkupString.Tests/MarkupTextTests.cs +++ b/MarkupString.Tests/MarkupTextTests.cs @@ -110,3 +110,55 @@ public async Task MarkupSet_StillInternsAfterTheTableFills() public async Task ToString_IsPlainText() => await Assert.That(MarkupText.Wrap(new Tag("b"), "x").ToString()).IsEqualTo("x"); } + +public class MarkupTextCreateTests +{ + private static readonly MarkupSet Bold = MarkupSet.Of(MarkupString.Ansi.AnsiCodeParser.Parse("h")); + private static readonly MarkupSet Red = MarkupSet.Of(MarkupString.Ansi.AnsiCodeParser.Parse("r")); + + [Test] + public async Task Create_IsWhatConcatenatingThePiecesMakes() + { + var created = MarkupText.Create("ab cd ef", [new Run(0, 2, Bold), new Run(6, 2, Red)]); + var concatenated = MarkupText.Concat( + [MarkupText.Wrap(Bold, "ab"), MarkupText.Plain(" cd "), MarkupText.Wrap(Red, "ef")]); + + await Assert.That(created.Text).IsEqualTo(concatenated.Text); + await Assert.That(created.Runs.SequenceEqual(concatenated.Runs)).IsTrue(); + } + + [Test] + public async Task Create_SortsClipsDropsAndMerges() + { + var created = MarkupText.Create("abcdef", [new Run(4, 10, Red), new Run(0, 2, Bold), new Run(2, 2, Bold), new Run(3, 0, Red)]); + + await Assert.That(created.Runs.SequenceEqual([new Run(0, 4, Bold), new Run(4, 2, Red)])).IsTrue(); + } + + [Test] + public async Task Create_CopiesTheRuns() + { + Run[] runs = [new Run(0, 2, Bold)]; + var created = MarkupText.Create("abc", runs); + runs[0] = new Run(1, 2, Red); + + await Assert.That(created.Runs[0]).IsEqualTo(new Run(0, 2, Bold)); + } + + [Test] + public async Task Create_WithNoRunsOrNoText_IsPlainOrEmpty() + { + await Assert.That(MarkupText.Create("", [new Run(0, 1, Bold)])).IsSameReferenceAs(MarkupText.Empty); + await Assert.That(MarkupText.Create("abc", []).Runs.IsEmpty).IsTrue(); + } + + [Test] + public async Task Create_RefusesOverlapsMissingSetsAndMisplacedPoints() + { + await Assert.That(() => MarkupText.Create("abcd", [new Run(0, 3, Bold), new Run(2, 2, Red)])).Throws(); + await Assert.That(() => MarkupText.Create("abcd", [default])).Throws(); + await Assert.That(() => MarkupText.Create("abcd", [new Run(0, 1, MarkupSet.Of(BellMarkup.Instance))])).Throws(); + var bell = MarkupText.Create($"a{BellMarkup.Character}", [new Run(1, 1, MarkupSet.Of(BellMarkup.Instance))]); + await Assert.That(bell.ToPlainText()).IsEqualTo("a"); + } +} diff --git a/MarkupString/MarkupText.cs b/MarkupString/MarkupText.cs index b4adc83..3368a3b 100644 --- a/MarkupString/MarkupText.cs +++ b/MarkupString/MarkupText.cs @@ -167,6 +167,34 @@ internal MarkupText(string text, ImmutableArray runs) public static MarkupText Wrap(IMarkup markup, string text) => Wrap(MarkupSet.Of(markup), text); + /// + /// Text with the styled spans given, built in one step: what concatenating a or + /// for each stretch makes, without the pieces. For a reader or parser + /// that already knows where each style starts and ends. + /// + /// + /// The runs are copied, then sorted by , clipped to the text, emptied ones dropped, + /// and neighbours carrying an equal set merged, as every text's runs are. Gaps between runs are plain text. + /// + /// + /// A run has no markup set, two runs overlap, or a point stands over something other than its own carrier. + /// + public static MarkupText Create(string text, ReadOnlySpan runs) + { + ArgumentNullException.ThrowIfNull(text); + if (text.Length == 0) return Empty; + if (runs.IsEmpty) return Plain(text); + + foreach (var run in runs) + { + if (run.Markups is null) throw new ArgumentException("Every run needs a markup set.", nameof(runs)); + var start = Math.Max(0, run.Start); + var end = Math.Min(text.Length, run.End); + if (end > start && HasPoint(run.Markups)) CheckPoints(run.Markups, text.Substring(start, end - start)); + } + return new MarkupText(text, ImmutableCollectionsMarshal.AsImmutableArray(runs.ToArray())); + } + /// /// A point in stands over something other than its own carrier. /// diff --git a/MarkupString/PublicAPI.Unshipped.txt b/MarkupString/PublicAPI.Unshipped.txt index 7cd9d0e..8de2a26 100644 --- a/MarkupString/PublicAPI.Unshipped.txt +++ b/MarkupString/PublicAPI.Unshipped.txt @@ -880,3 +880,4 @@ static MarkupString.ElementMarkup.operator ==(MarkupString.ElementMarkup? left, override MarkupString.Layout.Bounded.DrawLinear(MarkupString.Layout.LayoutContext! context, int width, System.Collections.Generic.IList! lines) -> void MarkupString.MarkupText.Split(MarkupString.MarkupText! delimiter, System.StringSplitOptions options) -> MarkupString.MarkupText![]! MarkupString.MarkupText.Split(string! delimiter, System.StringSplitOptions options) -> MarkupString.MarkupText![]! +static MarkupString.MarkupText.Create(string! text, System.ReadOnlySpan runs) -> MarkupString.MarkupText!