Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

### Added

- `MarkupText.Create(string, ReadOnlySpan<Run>)`: 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&#9;script:alert(1)"` passes `UrlPolicy.Safe` as a
Expand Down Expand Up @@ -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

Expand Down
91 changes: 70 additions & 21 deletions MarkupString.Ansi/AnsiEscapeParser.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
using System.Buffers;
namespace MarkupString.Ansi;

/// <summary>
Expand All @@ -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<MarkupText>();
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<char>.Shared.Rent(text.Length);
var runs = ArrayPool<Run>.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<Run>.Shared.Rent(runs.Length * 2);
runs.AsSpan(0, runCount).CopyTo(grown);
ArrayPool<Run>.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<char>.Shared.Return(chars);
ArrayPool<Run>.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)
/// <summary>The markup sets of the last four styles read, the oldest replaced first.</summary>
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;
}
}

/// <summary>Applies the sequence starting at <paramref name="position"/> and returns its length.</summary>
Expand Down
37 changes: 37 additions & 0 deletions MarkupString.Tests/Ansi/AnsiEscapeParserTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -240,4 +240,41 @@ public async Task UnterminatedCsi_ConsumesTheRest()
{
await Assert.That(AnsiEscapeParser.Parse($"abc{E}[31").Text).IsEqualTo("abc");
}

/// <summary>
/// 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.
/// </summary>
[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);
}

/// <summary>Text of nothing but sequences is empty.</summary>
[Test]
public async Task OnlySequences_IsEmpty()
{
await Assert.That(AnsiEscapeParser.Parse($"{E}[31m{E}[0m{E}[2J")).IsSameReferenceAs(MarkupText.Empty);
}

/// <summary>More styled stretches than the run buffer starts with.</summary>
[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));
}
}
52 changes: 52 additions & 0 deletions MarkupString.Tests/MarkupTextTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<ArgumentException>();
await Assert.That(() => MarkupText.Create("abcd", [default])).Throws<ArgumentException>();
await Assert.That(() => MarkupText.Create("abcd", [new Run(0, 1, MarkupSet.Of(BellMarkup.Instance))])).Throws<ArgumentException>();
var bell = MarkupText.Create($"a{BellMarkup.Character}", [new Run(1, 1, MarkupSet.Of(BellMarkup.Instance))]);
await Assert.That(bell.ToPlainText()).IsEqualTo("a");
}
}
28 changes: 28 additions & 0 deletions MarkupString/MarkupText.cs
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,34 @@ internal MarkupText(string text, ImmutableArray<Run> runs)

public static MarkupText Wrap(IMarkup markup, string text) => Wrap(MarkupSet.Of(markup), text);

/// <summary>
/// Text with the styled spans given, built in one step: what concatenating a <see cref="Plain(string)"/> or
/// <see cref="Wrap(MarkupSet, string)"/> for each stretch makes, without the pieces. For a reader or parser
/// that already knows where each style starts and ends.
/// </summary>
/// <remarks>
/// The runs are copied, then sorted by <see cref="Run.Start"/>, 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.
/// </remarks>
/// <exception cref="ArgumentException">
/// A run has no markup set, two runs overlap, or a point stands over something other than its own carrier.
/// </exception>
public static MarkupText Create(string text, ReadOnlySpan<Run> 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()));
}

/// <exception cref="ArgumentException">
/// A point in <paramref name="markups"/> stands over something other than its own carrier.
/// </exception>
Expand Down
1 change: 1 addition & 0 deletions MarkupString/PublicAPI.Unshipped.txt
Original file line number Diff line number Diff line change
Expand Up @@ -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<MarkupString.MarkupText!>! 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<MarkupString.Run> runs) -> MarkupString.MarkupText!
Loading