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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,24 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
- `Substring` and `Split` on styled text copy the runs they keep into an array of exactly that size.
Splitting a list of 1,000 coloured words allocates 132 KB instead of 312 KB.
- Enumerating a `MarkupSet` inside the library no longer boxes an enumerator.
- `DisplayWidth.Of` and `IndexAtWidth` count a stretch of printable ASCII with one vectorised scan:
2,000 characters measure in about 32 ns instead of 6 µs.
- `WrapLines`, `Shape` and `FormatColumn` measure each line only as far as the line. They measured the
whole rest of the paragraph for every line, so wrapping a 2,000-character paragraph at 78 columns took
89 µs; it takes 4.6 µs.
- Rendering shares one pair of pooled scratch buffers across all of a text's runs, hands a run's own
characters to its emitter when the format does not encode them, and `Render` returns its string from a
pooled buffer. The ANSI set emitter writes straight to the output when no other layer wraps the run.
Rendering 40 coloured runs to ANSI allocates 4.6 KB instead of 19.2 KB and takes a third of the time;
an 8-run line to HTML allocates 960 B instead of 4.5 KB.
- `AnsiColor.ToHex` returns a shared string for the palette colours.
- Kana, CJK ideographs and Hangul syllables are measured without the Unicode category and wide-range
lookups: a line of Chinese and Korean measures in less than half the time.
- Wrapping styled text in another layer (`Wrap(IMarkup, MarkupText)`, and `Insert` inside a run) builds its
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.

### Fixed

Expand Down
18 changes: 18 additions & 0 deletions MarkupString.Ansi/AnsiColor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,24 @@ public sealed record Rgb(byte R, byte G, byte B) : AnsiColor;
/// <see cref="Default"/>, which has no fixed value.
/// </summary>
public string ToHex()
{
// The palette colours have fixed values, so each one's string is made once and shared: an HTML
// render asks for one per styled run.
switch (this)
{
case Standard standard:
return StandardHex[(standard.Bright ? 8 : 0) + standard.Index] ??= FormatHex();
case Xterm xterm:
return XtermHex[xterm.Index] ??= FormatHex();
default:
return FormatHex();
}
}

private static readonly string?[] StandardHex = new string?[16];
private static readonly string?[] XtermHex = new string?[256];

private string FormatHex()
{
if (ToRgb() is not { } rgb)
{
Expand Down
40 changes: 23 additions & 17 deletions MarkupString.Ansi/AnsiEscapeParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,31 +19,37 @@ public static MarkupText Parse(string? text)
{
if (string.IsNullOrEmpty(text)) return MarkupText.Empty;

var first = text.IndexOf(Escape);
if (first < 0) return MarkupText.Plain(text);

var segments = new List<MarkupText>();
var style = AnsiStyle.None;
var position = 0;
// 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;

while (position < text.Length)
while (position >= 0)
{
if (text[position] != Escape)
{
position++;
continue;
}

if (position > segmentStart) segments.Add(Segment(text[segmentStart..position], style));
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;
}

if (segmentStart < text.Length) segments.Add(Segment(text[segmentStart..], style));
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) =>
style.IsNone ? MarkupText.Plain(text) : MarkupText.Wrap(new AnsiMarkup(style), text);
private static MarkupText Segment(string text, in AnsiStyle style, ref AnsiMarkup? markup)
{
if (style.IsNone) return MarkupText.Plain(text);
if (markup is null || !markup.Style.Equals(style)) markup = new AnsiMarkup(style);
return MarkupText.Wrap(markup, text);
}

/// <summary>Applies the sequence starting at <paramref name="position"/> and returns its length.</summary>
private static int ReadEscapeSequence(string text, int position, ref AnsiStyle style)
Expand Down Expand Up @@ -158,12 +164,12 @@ private static void ApplySgr(ReadOnlySpan<char> parameters, ref AnsiStyle style)
case 29: style = style with { StrikeThrough = false }; break;
case 55: style = style with { Overlined = false }; break;

case >= 30 and <= 37: style = style with { Foreground = new AnsiColor.Standard((byte)(code - 30), false) }; break;
case >= 30 and <= 37: style = style with { Foreground = AnsiColor.StandardOf((byte)(code - 30), false) }; break;
case 39: style = style with { Foreground = AnsiColor.Default.Instance }; break;
case >= 40 and <= 47: style = style with { Background = new AnsiColor.Standard((byte)(code - 40), false) }; break;
case >= 40 and <= 47: style = style with { Background = AnsiColor.StandardOf((byte)(code - 40), false) }; break;
case 49: style = style with { Background = AnsiColor.Default.Instance }; break;
case >= 90 and <= 97: style = style with { Foreground = new AnsiColor.Standard((byte)(code - 90), true) }; break;
case >= 100 and <= 107: style = style with { Background = new AnsiColor.Standard((byte)(code - 100), true) }; break;
case >= 90 and <= 97: style = style with { Foreground = AnsiColor.StandardOf((byte)(code - 90), true) }; break;
case >= 100 and <= 107: style = style with { Background = AnsiColor.StandardOf((byte)(code - 100), true) }; break;

case 38 or 48:
var colour = ReadExtendedColor(codes[..count], ref i);
Expand All @@ -188,7 +194,7 @@ private static void ApplySgr(ReadOnlySpan<char> parameters, ref AnsiStyle style)
{
var value = codes[index + 2];
index += 2;
return value is >= 0 and <= 255 ? new AnsiColor.Xterm((byte)value) : null;
return value is >= 0 and <= 255 ? AnsiColor.XtermOf((byte)value) : null;
}

if (codes[index + 1] == 2 && index + 4 < codes.Length)
Expand Down
17 changes: 12 additions & 5 deletions MarkupString.Ansi/Emitters/AnsiSetEmitter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,21 @@ public bool TryEmit(MarkupSet set, ReadOnlySpan<char> body, in EmitContext conte
var effective = AnsiEmitterSupport.Fold(set, context.Format).AtDepth(depth);
var previous = AnsiEmitterSupport.Fold(context.Previous, context.Format).AtDepth(depth);

using var core = new PooledCharWriter(body.Length + 32);
// The run is written around by the layers this package does not own, and a picture sends some of
// its output ahead of the row; with neither, the run goes straight to the output instead of
// through a scratch buffer.
var picture = Picture(set);
using var scratch = picture is not null || AnsiEmitterSupport.HasDelegatedLayer(set, context)
? new PooledCharWriter(body.Length + 32)
: null;
IBufferWriter<char> core = scratch is null ? output : scratch;
SgrWriter.Transition(previous, effective, core);
if (Picture(set) is { } picture)
if (picture is { } drawn)
{
// The run that starts the row draws all of it; the others in the same row draw nothing, so the row is
// as many cells as the text it stands over.
if (context.StartsRegion(picture.Image))
TerminalPictureWriter.Write(_pictureMethod, picture.Cells, picture.Pixels, effective, _options, core, output);
if (context.StartsRegion(drawn.Image))
TerminalPictureWriter.Write(_pictureMethod, drawn.Cells, drawn.Pixels, effective, _options, core, output);
}
else
{
Expand All @@ -68,7 +75,7 @@ public bool TryEmit(MarkupSet set, ReadOnlySpan<char> body, in EmitContext conte
// terminal coloured for whatever the connection writes next.
if (context.Next is null && AnsiEmitterSupport.LeavesState(effective)) SgrWriter.Reset(core);

AnsiEmitterSupport.WriteWrapped(set, core.WrittenSpan, context, output);
if (scratch is not null) AnsiEmitterSupport.WriteWrapped(set, scratch.WrittenSpan, context, output);
return true;
}

Expand Down
58 changes: 58 additions & 0 deletions MarkupString.Tests/AllocationTests.cs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
using MarkupString.Ansi;

/// <summary>
/// Bounds on what constructing a <see cref="MarkupText"/> costs. A caller that builds and discards
/// intermediates by the thousand — a parser, a formatter — renders almost none of them, so nothing
Expand Down Expand Up @@ -52,6 +54,26 @@ public async Task SplittingAndJoiningPlainText_AllocatesOnlyTheResults()
await Assert.That(perSplit).IsBetween(4_000, 12_000);
await Assert.That(perJoin).IsBetween(300, 1_200);
}

/// <summary>
/// Joining two short plain texts costs the joined string and its MarkupText: no run builder or empty
/// run array for text that has no runs.
/// </summary>
[Test]
public async Task ConcatenatingShortPlainText_AllocatesOnlyTheResult()
{
const int iterations = 10_000;
var a = MarkupText.Plain("hello ");
var b = MarkupText.Plain("world");
for (var i = 0; i < 100; i++) GC.KeepAlive(MarkupText.Concat(a, b));

var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < iterations; i++) GC.KeepAlive(MarkupText.Concat(a, b));
var perConcat = (GC.GetAllocatedBytesForCurrentThread() - before) / iterations;

// The 11-character string is 48 bytes and the MarkupText 48; a builder made it 152.
await Assert.That(perConcat).IsBetween(48, 112);
}
}

public class AnsiAllocationTests
Expand Down Expand Up @@ -83,4 +105,40 @@ public async Task WrappingPlainText_ReusesTheStylesSet()

await Assert.That(second.Runs[0].Markups).IsSameReferenceAs(first.Runs[0].Markups);
}

/// <summary>
/// Rendering styled text to a terminal costs the string it returns and little else: the runs share one
/// pair of pooled scratch buffers, and a run with nothing to wrap it is written straight to the output.
/// </summary>
[Test]
public async Task RenderingStyledTextToAnsi_AllocatesLittleBeyondTheResult()
{
const int iterations = 2_000;
var registry = MarkupRegistry.Empty.WithAnsi();
var green = MarkupString.Ansi.AnsiCodeParser.Parse("g");
var red = MarkupString.Ansi.AnsiCodeParser.Parse("hr");
// Forty runs of fifty characters, a third of them plain.
var parts = Enumerable.Range(0, 60).Select(i => i % 3 == 2
? MarkupText.Plain(new string('x', 50))
: MarkupText.Wrap(i % 3 == 0 ? green : red, new string('y', 50)));
var text = MarkupText.Concat(parts);
var expected = text.Render(MarkupFormat.Ansi, registry);

// Code the JIT has not yet promoted from its first tier can allocate where the optimised code does
// not, and promotion happens in the background a little after the first calls. The least of a few
// rounds a moment apart is the steady state.
var perRender = long.MaxValue;
for (var round = 0; round < 5 && perRender > 2 * expected.Length + 1_024; round++)
{
if (round > 0) Thread.Sleep(200);
var before = GC.GetAllocatedBytesForCurrentThread();
for (var i = 0; i < iterations; i++) GC.KeepAlive(text.Render(MarkupFormat.Ansi, registry));
perRender = Math.Min(perRender, (GC.GetAllocatedBytesForCurrentThread() - before) / iterations);
}

// The string alone is twice its length in bytes. Scratch writers allocated per run, and a growing
// output buffer copied into the string, came to three times that.
var result = 2 * expected.Length + 24;
await Assert.That(perRender).IsBetween(result, result + 1_024);
}
}
164 changes: 164 additions & 0 deletions MarkupString.Tests/DisplayWidthScanTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
using System.Globalization;
using System.Text;

/// <summary>
/// The measures count a stretch of printable ASCII with a vectorised scan and step through everything else
/// a character at a time. These check the two paths against the plain per-character walk they replaced,
/// over text that switches between them at every kind of boundary.
/// </summary>
public class DisplayWidthScanTests
{
/// <summary>Pieces chosen to sit on either side of a switch: controls, DEL, marks, a joiner, wide and paired characters.</summary>
private static readonly string[] Pieces =
[
"a", "Z", " ", "~", "hello world", "\u007F", "\t", "\n", "\r\n", "\u0007", "\u009B",
"́", "é", "‍", "日", "本語", "A", "ア", "가",
"\U0001F468‍\U0001F469", "\U0001F600", "\uD83D", "\uDE00", "é", "ำ", " ",
];

private static IEnumerable<string> Samples()
{
var random = new Random(20261112);
for (var i = 0; i < 2_000; i++)
{
var builder = new StringBuilder();
var count = random.Next(0, 12);
for (var j = 0; j < count; j++) builder.Append(Pieces[random.Next(Pieces.Length)]);
yield return builder.ToString();
}
}

/// <summary>What <see cref="DisplayWidth.Of(ReadOnlySpan{char}, ControlCharacterWidth)"/> computed before the scan.</summary>
private static int ReferenceOf(string text, ControlCharacterWidth controls)
{
var width = 0;
var afterJoiner = false;
foreach (var rune in text.EnumerateRunes())
{
var cells = DisplayWidth.OfRune(rune, controls);
if (afterJoiner && cells == 2) cells = 0;
afterJoiner = rune.Value == 0x200D;
width += cells;
}
return width;
}

/// <summary>What <see cref="DisplayWidth.IndexAtWidth(ReadOnlySpan{char}, int, ControlCharacterWidth)"/> computed before the scan.</summary>
private static int ReferenceIndexAtWidth(string text, int cells, ControlCharacterWidth controls)
{
if (cells <= 0) return 0;
var used = 0;
var position = 0;
while (position < text.Length)
{
int length, width;
if (text[position] is >= ' ' and < '\u007F'
&& (position + 1 >= text.Length || text[position + 1] is >= ' ' and < '\u007F'))
{
length = 1;
width = 1;
}
else
{
length = StringInfo.GetNextTextElementLength(text.AsSpan(position));
if (length <= 0) length = 1;
width = ReferenceOf(text.Substring(position, length), controls);
}
if (used + width > cells) return position;
used += width;
position += length;
}
return text.Length;
}

/// <summary>
/// The kana, ideograph and Hangul ranges answered before the category and wide-range lookups get what the lookups
/// give: two cells, as letters.
/// </summary>
[Test]
public async Task OfRune_IdeographAndHangulShortcut_AgreesWithTheTables()
{
var disagreeing = new List<int>();
foreach (var (start, end) in new[] { (0x3041, 0x3096), (0x30A1, 0x30FA), (0x3400, 0x4DBF), (0x4E00, 0x9FFF), (0xAC00, 0xD7A3) })
{
for (var value = start; value <= end; value++)
{
var rune = new Rune(value);
var wide = DisplayWidthTable.WideRanges.Any(r => r.Start <= value && value <= r.End);
if (Rune.GetUnicodeCategory(rune) != UnicodeCategory.OtherLetter || !wide || DisplayWidth.OfRune(rune) != 2)
disagreeing.Add(value);
}
}
await Assert.That(disagreeing).IsEmpty();
}

[Test]
public async Task Of_MatchesThePerCharacterWalk()
{
foreach (var text in Samples())
{
foreach (var controls in new[] { ControlCharacterWidth.Zero, ControlCharacterWidth.One })
await Assert.That(DisplayWidth.Of(text, controls)).IsEqualTo(ReferenceOf(text, controls));
}
}

/// <summary>
/// The bounded measure the line breaker asks: exact at or under the limit, and over it whenever the
/// whole text is, so "does the rest fit" gets the answer a full count gives.
/// </summary>
[Test]
public async Task Of_WithALimit_AgreesWithTheFullCountAboutFitting()
{
foreach (var text in Samples())
{
var full = ReferenceOf(text, ControlCharacterWidth.Zero);
for (var limit = 0; limit <= full + 1; limit++)
{
var bounded = DisplayWidth.Of(text, ControlCharacterWidth.Zero, limit);
await Assert.That(bounded <= limit).IsEqualTo(full <= limit);
if (full <= limit) await Assert.That(bounded).IsEqualTo(full);
}
}
}

[Test]
public async Task IndexAtWidth_MatchesThePerClusterWalk()
{
foreach (var text in Samples())
{
var full = ReferenceOf(text, ControlCharacterWidth.One);
for (var cells = 0; cells <= full + 1; cells++)
{
foreach (var controls in new[] { ControlCharacterWidth.Zero, ControlCharacterWidth.One })
{
await Assert.That(DisplayWidth.IndexAtWidth(text, cells, controls))
.IsEqualTo(ReferenceIndexAtWidth(text, cells, controls));
}
}
}
}

/// <summary>
/// Wrapping measured the rest of the paragraph for every line it cut, which made a long paragraph cost
/// the square of its length. Each line now measures no further than the line.
/// </summary>
[Test]
public async Task WrapLines_OnALongParagraph_BreaksAtTheLastSpaceThatFits()
{
var words = string.Join(" ", Enumerable.Range(0, 2_000).Select(i => new string((char)('a' + i % 26), 1 + i % 7)));
var lines = MarkupText.Plain(words).WrapLines(78);

await Assert.That(string.Join(" ", lines.Select(l => l.ToPlainText()))).IsEqualTo(words);
foreach (var line in lines)
{
await Assert.That(line.DisplayWidth).IsLessThanOrEqualTo(78);
await Assert.That(line.ToPlainText()).DoesNotStartWith(" ");
}
// Every line but the last was cut at a space: the next word would not have fitted.
for (var i = 0; i < lines.Length - 1; i++)
{
var next = lines[i + 1].ToPlainText().Split(' ')[0];
await Assert.That(lines[i].DisplayWidth + 1 + next.Length).IsGreaterThan(78);
}
}
}
Loading
Loading