diff --git a/CHANGELOG.md b/CHANGELOG.md index 3a4fb8b..3b6d961 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,22 @@ follows [Semantic Versioning](https://semver.org/spec/v2.0.0.html). `MarkupStringOptions.RefuseControlCharactersInLinks` turns it on for `AddMarkupString`. - `ElementMarkup`, data markup that numbers the element text is in, and `DecodeContext.NextElement()`. Stored by the serializer like the other shared markup. +- `MarkupText.Split(string, StringSplitOptions)` and `Split(MarkupText, StringSplitOptions)`. + `RemoveEmptyEntries` drops empty segments and `TrimEntries` trims white space off each, in the same pass + as the split, so splitting a list into its words no longer needs a second array to filter. + +### Changed + +- Appending to long text no longer copies it. `MarkupText.Concat` of 1,024 characters or more keeps its + parts and joins them the first time `Text` or `Runs` is read; `Length` and `Trim` with nothing to trim + don't join. A softcode accumulator (`setq(0,%q0…)` or `fold()` over 1,000 items) went from about 50 MB + to about 3 MB allocated per call in SharpMUSH. `Text`, `Runs` and the serializer see the same values as + before, and a text read from several threads at once is joined safely. +- `Splice`, and `Insert`, `Remove`, `Replace` and `ReplaceAll` on top of it, write the result once at its + final length instead of through a growing builder: about a third less allocated per `edit()`. +- `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. ### Fixed diff --git a/MarkupString.Tests/RepresentationTests.cs b/MarkupString.Tests/RepresentationTests.cs new file mode 100644 index 0000000..bb1d091 --- /dev/null +++ b/MarkupString.Tests/RepresentationTests.cs @@ -0,0 +1,385 @@ +using System.Text.Json; + +/// +/// How MarkupText stores and copies its text: deferred concatenation, one-copy splicing, exactly +/// sized runs on extraction, and splitting with options. Each result has to match what the plain, +/// eager construction gives. +/// +public class RepresentationTests +{ + private sealed record Tag(string Name) : IMarkup; + + private sealed class TagCodec : IMarkupCodec + { + public string Kind => "tag"; + public Type MarkupType => typeof(Tag); + public void Write(Utf8JsonWriter writer, IMarkup markup) => writer.WriteString("n", ((Tag)markup).Name); + public IMarkup Read(JsonElement element) => new Tag(element.GetProperty("n").GetString() ?? string.Empty); + } + + private static readonly Tag Red = new("red"); + private static readonly Tag Blue = new("blue"); + private static readonly MarkupRegistry Registry = MarkupRegistry.Empty.With(new TagCodec()); + + private static string Word(int i) => "w" + (i * 7919 % 100_000); + + /// A piece of letters, red, blue or unstyled by . + private static MarkupText Piece(int i, int length) + { + var text = new string((char)('a' + i % 26), length); + return (i % 3) switch + { + 0 => MarkupText.Plain(text), + 1 => MarkupText.Wrap(Red, text), + _ => MarkupText.Wrap(Blue, text), + }; + } + + /// The runs of laid end to end, coalesced as the constructor does. + private static List ExpectedRuns(IEnumerable pieces) + { + var runs = new List(); + var offset = 0; + foreach (var piece in pieces) + { + foreach (var run in piece.Runs) + { + var shifted = run with { Start = run.Start + offset }; + if (runs.Count > 0 && runs[^1].End == shifted.Start && runs[^1].Markups.Equals(shifted.Markups)) + runs[^1] = runs[^1] with { Length = runs[^1].Length + shifted.Length }; + else + runs.Add(shifted); + } + offset += piece.Length; + } + return runs; + } + + // ── Deferred concatenation ─────────────────────────────────────────────────── + + [Test] + public async Task Concat_BelowThreshold_JoinsAtOnce() + { + var text = MarkupText.Concat(Piece(1, 10), Piece(2, 10)); + await Assert.That(text.IsDeferred).IsFalse(); + } + + [Test] + public async Task Concat_AtThreshold_DefersAndKnowsItsLength() + { + var a = Piece(1, MarkupText.DeferThreshold / 2); + var b = Piece(2, MarkupText.DeferThreshold / 2); + var text = MarkupText.Concat(a, b); + + await Assert.That(text.IsDeferred).IsTrue(); + await Assert.That(text.Length).IsEqualTo(MarkupText.DeferThreshold); + await Assert.That(text.IsDeferred).IsTrue(); + await Assert.That(text.Text).IsEqualTo(a.Text + b.Text); + await Assert.That(text.IsDeferred).IsFalse(); + await Assert.That(text.Runs.SequenceEqual(ExpectedRuns([a, b]))).IsTrue(); + } + + /// + /// The softcode accumulator, setq(0,%q0<piece>) in a loop: thousands of appends to a + /// chain that is never read until the end. The join walks the chain without recursing. + /// + [Test] + public async Task Accumulator_OfManyAppends_JoinsToTheEagerResult() + { + var pieces = Enumerable.Range(0, 20_000).Select(i => Piece(i / 2, 7)).ToList(); + var text = MarkupText.Empty; + foreach (var piece in pieces) text = MarkupText.Concat(text, piece); + + await Assert.That(text.IsDeferred).IsTrue(); + await Assert.That(text.Length).IsEqualTo(20_000 * 7); + await Assert.That(text.Text).IsEqualTo(string.Concat(pieces.Select(p => p.Text))); + await Assert.That(text.Runs.SequenceEqual(ExpectedRuns(pieces))).IsTrue(); + } + + [Test] + public async Task ConcatOfSpan_OverThreshold_SkipsEmptyPartsAndMatchesEager() + { + MarkupText[] pieces = [Piece(1, 600), MarkupText.Empty, Piece(1, 300), Piece(2, 400)]; + var text = MarkupText.Concat(pieces); + + await Assert.That(text.IsDeferred).IsTrue(); + await Assert.That(text.Length).IsEqualTo(1_300); + await Assert.That(text.Text).IsEqualTo(string.Concat(pieces.Select(p => p.Text))); + // The two red pieces meet across the empty part and coalesce into one run. + await Assert.That(text.Runs.SequenceEqual(ExpectedRuns(pieces))).IsTrue(); + await Assert.That(text.Runs.Length).IsEqualTo(2); + } + + /// + /// SharpMUSH trims the end of each function argument it evaluates. Trimming an accumulator that + /// ends in no space must not join it, or every pass of the loop pays for a full copy again. + /// + [Test] + public async Task Trim_OnAChainWithNothingToTrim_LeavesItDeferred() + { + var text = MarkupText.Concat(Piece(1, 800), Piece(2, 800)); + var trimmed = text.Trim(TrimType.TrimBoth); + + await Assert.That(ReferenceEquals(trimmed, text)).IsTrue(); + await Assert.That(text.IsDeferred).IsTrue(); + } + + [Test] + public async Task Trim_OnAChainEndingInSpaces_TrimsAcrossParts() + { + var text = MarkupText.Concat([MarkupText.Plain(" "), Piece(1, 1_100), MarkupText.Plain(" ")]); + await Assert.That(text.IsDeferred).IsTrue(); + var trimmed = text.Trim(TrimType.TrimBoth); + + await Assert.That(trimmed.Text).IsEqualTo(new string('b', 1_100)); + await Assert.That(trimmed.Runs.SequenceEqual([new Run(0, 1_100, MarkupSet.Of(Red))])).IsTrue(); + } + + [Test] + public async Task OperationsOnAChain_MatchTheJoinedText() + { + var pieces = Enumerable.Range(0, 300).Select(i => Piece(i, 5)).ToList(); + var chain = MarkupText.Empty; + foreach (var piece in pieces) chain = MarkupText.Concat(chain, piece); + var eager = new MarkupText(string.Concat(pieces.Select(p => p.Text)), [.. ExpectedRuns(pieces)]); + + await Assert.That(chain.IsDeferred).IsTrue(); + await Assert.That(MarkupTextSerializer.Serialize(chain, Registry)).IsEqualTo(MarkupTextSerializer.Serialize(eager, Registry)); + await Assert.That(chain.Substring(700, 50).Runs.SequenceEqual(eager.Substring(700, 50).Runs)).IsTrue(); + await Assert.That(chain.Equals(eager)).IsTrue(); + } + + [Test] + public async Task Serializer_RoundTripsADeferredText() + { + var text = MarkupText.Concat([Piece(1, 700), Piece(0, 10), Piece(2, 700)]); + await Assert.That(text.IsDeferred).IsTrue(); + + var json = MarkupTextSerializer.Serialize(text, Registry); + var back = MarkupTextSerializer.Deserialize(json, Registry); + + await Assert.That(back.Text).IsEqualTo(text.Text); + await Assert.That(back.Runs.SequenceEqual(text.Runs)).IsTrue(); + } + + /// + /// A MarkupText is shared between threads. Readers racing to join one chain all see the same text + /// and runs, and Length never throws or reads a half-published state. + /// + [Test] + public async Task ConcurrentReaders_OfOneChain_AllSeeTheSameResult() + { + var pieces = Enumerable.Range(0, 400).Select(i => Piece(i, 9)).ToList(); + var expectedText = string.Concat(pieces.Select(p => p.Text)); + var expectedRuns = ExpectedRuns(pieces); + var failures = 0; + + for (var round = 0; round < 50; round++) + { + var chain = MarkupText.Empty; + foreach (var piece in pieces) chain = MarkupText.Concat(chain, piece); + using var start = new ManualResetEventSlim(); + var readers = Enumerable.Range(0, 8).Select(r => Task.Run(() => + { + start.Wait(); + for (var i = 0; i < 200; i++) + if (chain.Length != expectedText.Length) Interlocked.Increment(ref failures); + if (r % 2 == 0 && !chain.Runs.SequenceEqual(expectedRuns)) Interlocked.Increment(ref failures); + if (chain.Text != expectedText) Interlocked.Increment(ref failures); + if (!chain.Runs.SequenceEqual(expectedRuns)) Interlocked.Increment(ref failures); + })).ToArray(); + start.Set(); + await Task.WhenAll(readers); + } + + await Assert.That(failures).IsEqualTo(0); + } + + // ── Splice ─────────────────────────────────────────────────────────────────── + + [Test] + public async Task Splice_StyledEdits_KeepTheRunsBetweenThem() + { + var text = MarkupText.Concat([MarkupText.Wrap(Red, "aaaa"), MarkupText.Plain("bbbb"), MarkupText.Wrap(Blue, "cccc")]); + var result = text.Splice([new Edit(2, 4, MarkupText.Wrap(Blue, "X")), new Edit(9, 0, MarkupText.Plain("YY"))]); + + await Assert.That(result.Text).IsEqualTo("aaXbbcYYccc"); + await Assert.That(result.Runs.SequenceEqual([ + new Run(0, 2, MarkupSet.Of(Red)), + new Run(2, 1, MarkupSet.Of(Blue)), + new Run(5, 1, MarkupSet.Of(Blue)), + new Run(8, 3, MarkupSet.Of(Blue)), + ])).IsTrue(); + } + + /// More than 64 edits take their ranges from a rented buffer instead of the stack. + [Test] + public async Task ReplaceAll_WithManyHits_MatchesStringReplace() + { + var source = string.Join(";", Enumerable.Range(0, 500).Select(Word)); + var text = MarkupText.Concat(source.Split(';').Select((w, i) => i % 2 == 0 ? MarkupText.Wrap(Red, w + ";") : MarkupText.Plain(w + ";")).ToArray()); + var result = text.ReplaceAll(";", MarkupText.Wrap(Blue, "<>")); + + await Assert.That(result.Text).IsEqualTo((source + ";").Replace(";", "<>")); + await Assert.That(result.Runs.Count(r => r.Markups.Equals(MarkupSet.Of(Blue)))).IsEqualTo(500); + await Assert.That(result.Runs.Count(r => r.Markups.Equals(MarkupSet.Of(Red)))).IsEqualTo(250); + } + + [Test] + public async Task Splice_PlainTextAndPlainReplacements_HasNoRuns() + { + var result = MarkupText.Plain("hello world").Splice([new Edit(0, 5, MarkupText.Plain("HELLO")), new Edit(6, 5, MarkupText.Empty)]); + await Assert.That(result.Text).IsEqualTo("HELLO "); + await Assert.That(result.Runs.IsEmpty).IsTrue(); + } + + // ── Extraction ─────────────────────────────────────────────────────────────── + + /// + /// Substring copies the runs overlapping its range into an array of exactly their number. Checked + /// against clipping every run by hand, over random styled text with combining marks, so ranges + /// that snap back from a mark are covered too. + /// + [Test] + public async Task Substring_ClipsRunsLikeAReferenceClip() + { + var random = new Random(42); + Tag[] tags = [Red, Blue, new("green"), new("bold")]; + var mismatches = 0; + for (var trial = 0; trial < 500; trial++) + { + var parts = new List(); + for (var i = random.Next(1, 30); i > 0; i--) + { + var s = new string((char)('a' + random.Next(26)), random.Next(1, 6)) + (random.Next(8) == 0 ? "é" : ""); + parts.Add(random.Next(3) == 0 ? MarkupText.Plain(s) : MarkupText.Wrap(tags[random.Next(tags.Length)], s)); + } + var text = MarkupText.Concat(parts); + for (var k = 0; k < 40; k++) + { + var start = random.Next(-2, text.Length + 2); + var sub = text.Substring(start, random.Next(0, text.Length + 2)); + if (sub.Length == 0) + { + if (!sub.Runs.IsEmpty) mismatches++; + continue; + } + // The text has no cluster longer than "e" + U+0301, so a start snaps back by at most one. + var from = Math.Max(0, start); + if (from < text.Length && text.Text[from] == '́') from--; + var to = from + sub.Length; + var expected = text.Runs + .Where(r => r.Start < to && r.End > from) + .Select(r => new Run(Math.Max(r.Start, from) - from, Math.Min(r.End, to) - Math.Max(r.Start, from), r.Markups)); + if (text.Text[from..to] != sub.Text || !expected.SequenceEqual(sub.Runs)) mismatches++; + } + } + await Assert.That(mismatches).IsEqualTo(0); + } + + // ── Split with options ─────────────────────────────────────────────────────── + + [Test] + public async Task Split_RemoveEmptyEntries_DropsEmptyWords() + { + var parts = MarkupText.Plain(" a b c ").Split(" ", StringSplitOptions.RemoveEmptyEntries); + await Assert.That(parts.Select(p => p.Text)).IsEquivalentTo(["a", "b", "c"]); + } + + [Test] + public async Task Split_TrimEntries_TrimsEachSegmentButKeepsEmptyOnes() + { + var parts = MarkupText.Plain(" a ,, b\t,").Split(",", StringSplitOptions.TrimEntries); + await Assert.That(parts.Select(p => p.Text).ToArray()).IsEquivalentTo(["a", "", "b", ""]); + } + + [Test] + public async Task Split_TrimAndRemoveEmpty_DropsSegmentsThatTrimToNothing() + { + var parts = MarkupText.Plain(" a , ,b ").Split(",", StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries); + await Assert.That(parts.Select(p => p.Text).ToArray()).IsEquivalentTo(["a", "b"]); + } + + [Test] + public async Task Split_TrimEntries_WithNoDelimiterFound_TrimsTheWholeText() + { + var parts = MarkupText.Plain(" word ").Split(",", StringSplitOptions.TrimEntries); + await Assert.That(parts.Select(p => p.Text).ToArray()).IsEquivalentTo(["word"]); + } + + [Test] + public async Task Split_UndefinedOption_Throws() + { + await Assert.That(() => MarkupText.Plain("a b").Split(" ", (StringSplitOptions)4)).Throws(); + } + + [Test] + public async Task Split_MarkupDelimiter_UsesItsPlainText() + { + var parts = MarkupText.Plain("a--b----c").Split(MarkupText.Wrap(Red, "--"), StringSplitOptions.RemoveEmptyEntries); + await Assert.That(parts.Select(p => p.Text).ToArray()).IsEquivalentTo(["a", "b", "c"]); + } + + /// + /// The options must give exactly what splitting and then filtering gives, styled runs included, + /// on random lists of words, spaces and tabs. + /// + [Test] + public async Task Split_WithOptions_MatchesSplitThenFilter() + { + var random = new Random(7); + var mismatches = 0; + for (var trial = 0; trial < 500; trial++) + { + var parts = new List(); + for (var i = random.Next(0, 20); i > 0; i--) + { + var piece = random.Next(4) switch + { + 0 => " ", + 1 => "\t", + 2 => " ", + _ => Word(random.Next(1000)), + }; + parts.Add(random.Next(2) == 0 ? MarkupText.Plain(piece) : MarkupText.Wrap(random.Next(2) == 0 ? Red : Blue, piece)); + } + var text = MarkupText.Concat(parts); + + foreach (var options in new[] { StringSplitOptions.None, StringSplitOptions.RemoveEmptyEntries, StringSplitOptions.TrimEntries, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries }) + { + IEnumerable expected = text.Split(" "); + if (options.HasFlag(StringSplitOptions.TrimEntries)) + expected = expected.Select(s => s.Trim(TrimType.TrimBoth, " \t")); + if (options.HasFlag(StringSplitOptions.RemoveEmptyEntries)) + expected = expected.Where(s => s.Length > 0); + var actual = text.Split(" ", options); + if (!expected.Select(s => (s.Text, Runs: string.Join(",", s.Runs))).SequenceEqual(actual.Select(s => (s.Text, Runs: string.Join(",", s.Runs))))) + mismatches++; + } + } + await Assert.That(mismatches).IsEqualTo(0); + } + + /// + /// A coloured list split into its words: each word carries one run, so its runs are one exact + /// array, not a default builder grown for eight and copied out. + /// + [Test] + public async Task SplittingColouredList_AllocatesNoRunBuilders() + { + const int iterations = 2_000; + var list = MarkupText.Concat(Enumerable.Range(0, 100) + .SelectMany(i => new[] { MarkupText.Wrap(i % 2 == 0 ? Red : Blue, Word(i)), MarkupText.Space }) + .ToArray()); + _ = list.Text; + for (var i = 0; i < 100; i++) GC.KeepAlive(list.Split(" ", StringSplitOptions.RemoveEmptyEntries)); + + var before = GC.GetAllocatedBytesForCurrentThread(); + for (var i = 0; i < iterations; i++) GC.KeepAlive(list.Split(" ", StringSplitOptions.RemoveEmptyEntries)); + var perSplit = (GC.GetAllocatedBytesForCurrentThread() - before) / iterations; + + // 100 words: the array, and a string, a MarkupText and a one-run array each (about 13 KB). A + // builder per word came to about 31 KB. + await Assert.That(perSplit).IsBetween(6_000, 18_000); + } +} diff --git a/MarkupString/AsciiFold.cs b/MarkupString/AsciiFold.cs index 234a346..7bda837 100644 --- a/MarkupString/AsciiFold.cs +++ b/MarkupString/AsciiFold.cs @@ -253,7 +253,7 @@ public MarkupText Fold(MarkupText text) { List<(int Start, int End)>? ranges = null; foreach (var run in runs) - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) if (markup is IPointMarkup) { (ranges ??= []).Add((run.Start, run.End)); @@ -275,7 +275,7 @@ public MarkupText Fold(MarkupText text) StandInMarkup? found = null; // One whose text is not printable ASCII (built directly, or read from the wire) is ignored, so the // covered text folds as any other would. - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) if (markup is StandInMarkup standIn && IsPrintableAscii(standIn.Text)) { found = standIn; diff --git a/MarkupString/MarkupSet.cs b/MarkupString/MarkupSet.cs index 6adfbc0..b4b3930 100644 --- a/MarkupString/MarkupSet.cs +++ b/MarkupString/MarkupSet.cs @@ -139,6 +139,9 @@ private static MarkupSet Canonical(MarkupSet candidate) return canonical; } + /// The layers, innermost first, without boxing an enumerator as does. + internal ReadOnlySpan Items => _items; + public int Count => _items.Length; public IMarkup this[int index] => _items[index]; public IMarkup Innermost => _items[0]; diff --git a/MarkupString/MarkupText.Operations.cs b/MarkupString/MarkupText.Operations.cs index e5410a3..da05593 100644 --- a/MarkupString/MarkupText.Operations.cs +++ b/MarkupString/MarkupText.Operations.cs @@ -1,3 +1,4 @@ +using System.Buffers; using System.Collections.Immutable; using System.Runtime.InteropServices; using System.Text; @@ -77,9 +78,22 @@ private MarkupText ExtractRange(int from, int to) // Text with no runs has none to clip: no builder to fill, and an empty array to share. if (Runs.IsDefaultOrEmpty) return new MarkupText(Text[from..to], ImmutableArray.Empty); - var runs = ImmutableArray.CreateBuilder(); - ClipInto(from, to, -from, runs); - return new MarkupText(Text[from..to], runs.ToImmutable()); + // Runs are sorted and disjoint, so the ones overlapping [from, to) are a contiguous slice: + // size the result exactly instead of growing a default builder and copying it out. + var first = FirstRunIndexAt(from); + if (Runs[first].End <= from) first++; + var last = first; + while (last < Runs.Length && Runs[last].Start < to) last++; + if (last == first) return new MarkupText(Text[from..to], ImmutableArray.Empty); + + var clipped = new Run[last - first]; + for (var i = first; i < last; i++) + { + var run = Runs[i]; + var start = Math.Max(run.Start, from); + clipped[i - first] = new Run(start - from, Math.Min(run.End, to) - start, run.Markups); + } + return new MarkupText(Text[from..to], ImmutableCollectionsMarshal.AsImmutableArray(clipped)); } /// @@ -175,30 +189,62 @@ public MarkupText TruncateToWidth(int cells, CutFrom from) /// Splits on the plain text of ; its markup is ignored. public MarkupText[] Split(MarkupText delimiter) => Split(delimiter.Text); + /// + /// Splits on the plain text of , its markup ignored, as + /// does. + /// + public MarkupText[] Split(MarkupText delimiter, StringSplitOptions options) => Split(delimiter.Text, options); + /// /// Splits on every non-overlapping ordinal occurrence of . An /// empty text yields no segments; an empty delimiter yields this text unsplit. /// - public MarkupText[] Split(string delimiter) + public MarkupText[] Split(string delimiter) => Split(delimiter, StringSplitOptions.None); + + /// + /// Splits on every non-overlapping ordinal occurrence of , as + /// does, then applies to each segment in + /// the same pass: drops white space + /// () from both ends of a segment, and + /// leaves out segments that are empty, after + /// trimming when both are given. Splitting a list on spaces with + /// gives its words without filtering a second + /// array. + /// + /// holds an undefined flag. + public MarkupText[] Split(string delimiter, StringSplitOptions options) { ArgumentNullException.ThrowIfNull(delimiter); - if (Length == 0) return []; - if (delimiter.Length == 0) return [this]; + const StringSplitOptions all = StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries; + if ((options & ~all) != 0) throw new ArgumentException($"Undefined flags: {options & ~all}.", nameof(options)); + var removeEmpty = (options & StringSplitOptions.RemoveEmptyEntries) != 0; + var trim = (options & StringSplitOptions.TrimEntries) != 0; + if (Length == 0) return []; + var text = Text; // Counting first sizes the result exactly, so there is no list of positions to grow and copy. - var count = Text.AsSpan().Count(delimiter.AsSpan()); - if (count == 0) return [this]; + var count = delimiter.Length == 0 ? 0 : text.AsSpan().Count(delimiter.AsSpan()); + if (count == 0 && !trim) return [this]; var segments = new MarkupText[count + 1]; + var kept = 0; var cursor = 0; - for (var i = 0; i < count; i++) + for (var i = 0; i <= count; i++) { - var found = Text.IndexOf(delimiter, cursor, StringComparison.Ordinal); - segments[i] = Substring(cursor, found - cursor); + var found = i < count ? text.IndexOf(delimiter, cursor, StringComparison.Ordinal) : text.Length; + var start = cursor; + var end = found; + if (trim) + { + while (start < end && char.IsWhiteSpace(text[start])) start++; + while (end > start && char.IsWhiteSpace(text[end - 1])) end--; + } + // The last segment runs to the end of the text, so take it as Substring(start) does. + var segment = start == end ? Empty : end == text.Length ? Substring(start) : Substring(start, end - start); + if (!removeEmpty || segment.Length > 0) segments[kept++] = segment; cursor = found + delimiter.Length; } - segments[^1] = Substring(cursor); - return segments; + return kept == segments.Length ? segments : segments[..kept]; } /// Removes leading and/or trailing spaces from the requested end(s). @@ -217,10 +263,11 @@ public MarkupText Trim(TrimType type, string chars) var start = 0; var end = Length; + // CharAt rather than Text: trimming an accumulator that has nothing to trim must not join it. if (type is TrimType.TrimStart or TrimType.TrimBoth) - while (start < end && chars.Contains(Text[start])) start++; + while (start < end && chars.Contains(CharAt(start))) start++; if (type is TrimType.TrimEnd or TrimType.TrimBoth) - while (end > start && chars.Contains(Text[end - 1])) end--; + while (end > start && chars.Contains(CharAt(end - 1))) end--; return start == 0 && end == Length ? this : Substring(start, end - start); } @@ -305,7 +352,7 @@ public MarkupText Repeat(int count) if (Runs.IsDefaultOrEmpty) return new MarkupText(text, ImmutableArray.Empty); // One style over the whole text: the copies would coalesce into one run anyway. A point // marks a single carrier, so its copies stay apart. - if (Runs is [{ Start: 0 } whole] && whole.Length == Length && !whole.Markups.Any(m => m is IPointMarkup)) + if (Runs is [{ Start: 0 } whole] && whole.Length == Length && !HasPoint(whole.Markups)) return new MarkupText(text, [new Run(0, text.Length, whole.Markups)]); var runs = ImmutableArray.CreateBuilder(Runs.Length * count); @@ -372,37 +419,90 @@ public MarkupText Splice(ReadOnlySpan edits) { if (edits.Length == 0) return this; - var text = new StringBuilder(Length); - var runs = ImmutableArray.CreateBuilder(); - var position = 0; - var previousEnd = 0; - foreach (var edit in edits) + var source = Text; + int[]? rented = null; + var ranges = edits.Length <= 64 + ? stackalloc int[edits.Length * 2] + : (rented = ArrayPool.Shared.Rent(edits.Length * 2)).AsSpan(0, edits.Length * 2); + try { - if (edit.Start < 0 || edit.Start > Length) - throw new ArgumentOutOfRangeException(nameof(edits), edit.Start, "Edit starts outside the text."); - if (edit.Length < 0 || edit.Length > Length - edit.Start) - throw new ArgumentOutOfRangeException(nameof(edits), edit.Length, "Edit ends outside the text."); - if (edit.Start < previousEnd) - throw new ArgumentException("Edits must be sorted by start and must not overlap.", nameof(edits)); - previousEnd = edit.Start + edit.Length; - - var start = Math.Max(position, Graphemes.SnapStart(Text, edit.Start)); - var end = edit.Length == 0 ? start : Math.Max(start, Graphemes.SnapEnd(Text, edit.Start + edit.Length)); - - ClipInto(position, start, text.Length - position, runs); - text.Append(Text, position, start - position); - - var replacement = edit.Replacement ?? Empty; - var offset = text.Length; - text.Append(replacement.Text); - foreach (var run in replacement.Runs) runs.Add(run with { Start = run.Start + offset }); - - position = end; + // Pass 1: check, snap each range outward to cluster boundaries, and size the result, so the + // text is written once at its final length instead of through a growing builder. + var position = 0; + var previousEnd = 0; + var length = 0; + var runCount = Runs.Length + edits.Length; + for (var i = 0; i < edits.Length; i++) + { + var edit = edits[i]; + if (edit.Start < 0 || edit.Start > Length) + throw new ArgumentOutOfRangeException(nameof(edits), edit.Start, "Edit starts outside the text."); + if (edit.Length < 0 || edit.Length > Length - edit.Start) + throw new ArgumentOutOfRangeException(nameof(edits), edit.Length, "Edit ends outside the text."); + if (edit.Start < previousEnd) + throw new ArgumentException("Edits must be sorted by start and must not overlap.", nameof(edits)); + previousEnd = edit.Start + edit.Length; + + var start = Math.Max(position, Graphemes.SnapStart(source, edit.Start)); + var end = edit.Length == 0 ? start : Math.Max(start, Graphemes.SnapEnd(source, edit.Start + edit.Length)); + ranges[i * 2] = start; + ranges[i * 2 + 1] = end; + + var replacement = edit.Replacement ?? Empty; + length = checked(length + (start - position) + replacement.Length); + runCount += replacement.Runs.Length; + position = end; + } + length = checked(length + (Length - position)); + + // Pass 2: the text. + var text = string.Create(length, new SpliceState(source, edits, ranges), static (span, state) => + { + var from = 0; + var written = 0; + for (var i = 0; i < state.Edits.Length; i++) + { + var start = state.Ranges[i * 2]; + state.Source.AsSpan(from, start - from).CopyTo(span[written..]); + written += start - from; + var replacement = (state.Edits[i].Replacement ?? Empty).Text; + replacement.AsSpan().CopyTo(span[written..]); + written += replacement.Length; + from = state.Ranges[i * 2 + 1]; + } + state.Source.AsSpan(from).CopyTo(span[written..]); + }); + + // Pass 3: the runs, unless neither side has any. + if (Runs.IsDefaultOrEmpty && runCount == edits.Length) return new MarkupText(text, ImmutableArray.Empty); + + var runs = ImmutableArray.CreateBuilder(runCount); + position = 0; + var output = 0; + for (var i = 0; i < edits.Length; i++) + { + var start = ranges[i * 2]; + ClipInto(position, start, output - position, runs); + output += start - position; + var replacement = edits[i].Replacement ?? Empty; + foreach (var run in replacement.Runs) runs.Add(run with { Start = run.Start + output }); + output += replacement.Length; + position = ranges[i * 2 + 1]; + } + ClipInto(position, Length, output - position, runs); + return new MarkupText(text, runs.Count == runs.Capacity ? runs.MoveToImmutable() : runs.ToImmutable()); + } + finally + { + if (rented is not null) ArrayPool.Shared.Return(rented); } + } - ClipInto(position, Length, text.Length - position, runs); - text.Append(Text, position, Length - position); - return new MarkupText(text.ToString(), runs.ToImmutable()); + private readonly ref struct SpliceState(string source, ReadOnlySpan edits, ReadOnlySpan ranges) + { + public string Source { get; } = source; + public ReadOnlySpan Edits { get; } = edits; + public ReadOnlySpan Ranges { get; } = ranges; } /// @@ -541,6 +641,13 @@ private int FirstRunIndexAt(int position) return result; } + private static bool HasPoint(MarkupSet markups) + { + foreach (var markup in markups.Items) + if (markup is IPointMarkup) return true; + return false; + } + /// Layers over every run and gap of . private static MarkupText WrapWith(MarkupText inner, MarkupSet outer) { @@ -559,7 +666,7 @@ private static MarkupText WrapWith(MarkupText inner, MarkupSet outer) private static MarkupSet Layer(MarkupSet inner, MarkupSet outer) { var result = inner; - foreach (var markup in outer) result = result.Append(markup); + foreach (var markup in outer.Items) result = result.Append(markup); return result; } } diff --git a/MarkupString/MarkupText.cs b/MarkupString/MarkupText.cs index 70ef6c0..56dced8 100644 --- a/MarkupString/MarkupText.cs +++ b/MarkupString/MarkupText.cs @@ -14,9 +14,131 @@ public sealed partial class MarkupText : IEquatable public static readonly MarkupText Space = new(" ", ImmutableArray.Empty); public static readonly MarkupText NewLine = new("\n", ImmutableArray.Empty); - public string Text { get; } - public ImmutableArray Runs { get; } - public int Length => Text.Length; + /// The characters. On text built by a deferred concatenation, the first read joins the parts. + public string Text => Volatile.Read(ref _payload) as string ?? Flatten(); + + /// The styled spans over , sorted and coalesced. + public ImmutableArray Runs + { + get + { + if (Volatile.Read(ref _payload) is not string) Flatten(); + return _runs; + } + } + + public int Length => Volatile.Read(ref _payload) switch + { + // One read: another thread may join the parts between two reads of the field. + string text => text.Length, + var deferred => ((Deferred)deferred).Length, + }; + + /// + /// The text as a , or, until the first read joins them, a + /// concatenation. One field for both keeps every MarkupText the size it was. + /// + private object _payload; + + /// The parts of a concatenation not yet joined, and their total length. + private sealed class Deferred(MarkupText[] parts, int length) + { + public readonly MarkupText[] Parts = parts; + public readonly int Length = length; + } + private ImmutableArray _runs; + + /// Whether this text is a concatenation that has not been joined yet. + internal bool IsDeferred => Volatile.Read(ref _payload) is Deferred; + + /// + /// The length from which records its parts instead of + /// copying them. Below it a copy is cheap and the string is likely to be read soon anyway. + /// + internal const int DeferThreshold = 1024; + + private MarkupText(MarkupText[] parts, int length) + { + _payload = new Deferred(parts, length); + } + + /// + /// The character at , found without joining a deferred concatenation. The + /// last character of an accumulator is one step away; the first is as deep as the chain. + /// + private char CharAt(int index) + { + var node = this; + while (true) + { + var payload = Volatile.Read(ref node._payload); + if (payload is string text) return text[index]; + foreach (var part in ((Deferred)payload).Parts) + { + if (index < part.Length) + { + node = part; + break; + } + index -= part.Length; + } + } + } + + /// + /// Joins a deferred concatenation. The walk is iterative, because a softcode loop can chain + /// thousands of appends. Runs are written before the text is published; two threads racing here + /// both build the same text, and the one that loses throws its copy away. + /// + private string Flatten() + { + if (Volatile.Read(ref _payload) is not Deferred deferred) return (string)_payload; + var parts = deferred.Parts; + + var leaves = new List(); + var stack = new Stack(); + for (var i = parts.Length - 1; i >= 0; i--) stack.Push(parts[i]); + var totalRuns = 0; + while (stack.Count > 0) + { + var node = stack.Pop(); + if (Volatile.Read(ref node._payload) is Deferred { Parts: var inner }) + { + for (var i = inner.Length - 1; i >= 0; i--) stack.Push(inner[i]); + continue; + } + // Either flat from the start, or joined by another reader since: its text and runs are set. + leaves.Add(node); + totalRuns += node._runs.IsDefault ? 0 : node._runs.Length; + } + + var text = string.Create(deferred.Length, leaves, static (span, leaves) => + { + var offset = 0; + foreach (var leaf in leaves) + { + var t = (string)leaf._payload; + t.AsSpan().CopyTo(span[offset..]); + offset += t.Length; + } + }); + + var runs = ImmutableArray.Empty; + if (totalRuns > 0) + { + var builder = ImmutableArray.CreateBuilder(totalRuns); + var start = 0; + foreach (var leaf in leaves) + { + foreach (var run in leaf._runs) builder.Add(run with { Start = run.Start + start }); + start += leaf.Length; + } + runs = Normalise(builder.MoveToImmutable(), text, text.Length); + } + + _runs = runs; + return Interlocked.CompareExchange(ref _payload, text, deferred) as string ?? text; + } /// /// Constructs a from raw text and candidate runs. Normalises the @@ -25,8 +147,8 @@ public sealed partial class MarkupText : IEquatable /// internal MarkupText(string text, ImmutableArray runs) { - Text = text; - Runs = Normalise(runs, text, text.Length); + _payload = text; + _runs = Normalise(runs, text, text.Length); } public static MarkupText Plain(string text) => text.Length switch @@ -93,10 +215,11 @@ public static MarkupText Concat(MarkupText a, MarkupText b) { if (a.Length == 0) return b; if (b.Length == 0) return a; + if (a.Length + b.Length >= DeferThreshold) return new MarkupText([a, b], checked(a.Length + b.Length)); var runs = ImmutableArray.CreateBuilder(a.Runs.Length + b.Runs.Length); runs.AddRange(a.Runs); foreach (var run in b.Runs) runs.Add(run with { Start = run.Start + a.Length }); - return new MarkupText(a.Text + b.Text, runs.ToImmutable()); + return new MarkupText(a.Text + b.Text, runs.MoveToImmutable()); } public static MarkupText Concat(ReadOnlySpan parts) @@ -108,13 +231,20 @@ public static MarkupText Concat(ReadOnlySpan parts) foreach (var p in parts) { if (p.Length == 0) continue; - totalLength += p.Length; - totalRuns += p.Runs.Length; + totalLength = checked(totalLength + p.Length); nonEmpty++; last = p; } if (nonEmpty == 0) return Empty; if (nonEmpty == 1) return last!; + if (totalLength >= DeferThreshold) + { + var kept = new MarkupText[nonEmpty]; + var k = 0; + foreach (var p in parts) if (p.Length > 0) kept[k++] = p; + return new MarkupText(kept, totalLength); + } + foreach (var p in parts) totalRuns += p.Runs.Length; var text = string.Create(totalLength, parts, static (span, parts) => { var offset = 0; @@ -246,7 +376,7 @@ public MarkupText WithoutVisualMarkup() var hasData = false; foreach (var run in Runs) { - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) { if (markup is not IDataMarkup) continue; hasData = true; @@ -265,7 +395,7 @@ public MarkupText WithoutVisualMarkup() if (IsPoint(run)) continue; var data = new List(); - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) if (markup is IDataMarkup) data.Add(markup); var body = Text.Substring(run.Start, run.Length); parts.Add(data.Count == 0 ? Plain(body) : Wrap(MarkupSet.Of(data), body)); @@ -288,7 +418,7 @@ internal MarkupText WithoutMarkup(Func drop) var dropping = false; foreach (var run in Runs) { - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) { if (!drop(markup)) continue; dropping = true; @@ -302,7 +432,7 @@ internal MarkupText WithoutMarkup(Func drop) foreach (var run in Runs) { var kept = new List(run.Markups.Count); - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) if (!drop(markup)) kept.Add(markup); if (kept.Count == run.Markups.Count) builder.Add(run); else if (kept.Count > 0) builder.Add(run with { Markups = MarkupSet.Of(kept) }); @@ -345,7 +475,7 @@ private string WithoutPoints() private static bool IsPoint(Run run) { - foreach (var markup in run.Markups) + foreach (var markup in run.Markups.Items) if (markup is IPointMarkup) return true; return false; } @@ -361,7 +491,7 @@ private static bool IsPoint(Run run) /// Every point in the set marks only its own carrier. private static void CheckPoints(MarkupSet markups, string text) { - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is IPointMarkup point) CheckPoint(point, text); } @@ -396,7 +526,7 @@ private static bool IsCarriedBy(IPointMarkup point, ReadOnlySpan text) private static MarkupSet WithoutMisplacedPoints(MarkupSet markups, ReadOnlySpan text) { var keep = true; - foreach (var markup in markups) + foreach (var markup in markups.Items) { if (markup is IPointMarkup point && !IsCarriedBy(point, text)) { @@ -408,7 +538,7 @@ private static MarkupSet WithoutMisplacedPoints(MarkupSet markups, ReadOnlySpan< if (keep) return markups; var kept = new List(markups.Count); - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is not IPointMarkup point || IsCarriedBy(point, text)) kept.Add(markup); diff --git a/MarkupString/MarkupTextRenderer.cs b/MarkupString/MarkupTextRenderer.cs index 561a3e5..0b2ae53 100644 --- a/MarkupString/MarkupTextRenderer.cs +++ b/MarkupString/MarkupTextRenderer.cs @@ -471,7 +471,7 @@ private static TextEncoding EncodingFor(MarkupSet markups, MarkupFormat format, private static int CountPoints(MarkupSet markups) { var points = 0; - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is IPointMarkup) points++; return points; } @@ -491,7 +491,7 @@ private static bool WritePoints( IBufferWriter output) { var written = false; - foreach (var markup in markups) + foreach (var markup in markups.Items) { if (markup is not IPointMarkup point) continue; @@ -510,13 +510,13 @@ private static bool WritePoints( private static MarkupSet? WithoutData(MarkupSet markups) { var data = 0; - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is IDataMarkup) data++; if (data == 0) return markups; if (data == markups.Count) return null; var rest = new List(markups.Count - data); - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is not IDataMarkup) rest.Add(markup); return MarkupSet.Of(rest); } @@ -527,7 +527,7 @@ private static bool WritePoints( if (markups.Count == points) return null; var rest = new List(markups.Count - points); - foreach (var markup in markups) + foreach (var markup in markups.Items) if (markup is not IPointMarkup) rest.Add(markup); return MarkupSet.Of(rest); } diff --git a/MarkupString/MarkupTextSerializer.cs b/MarkupString/MarkupTextSerializer.cs index cac315b..e5aa990 100644 --- a/MarkupString/MarkupTextSerializer.cs +++ b/MarkupString/MarkupTextSerializer.cs @@ -148,7 +148,7 @@ internal static void Write(Utf8JsonWriter writer, MarkupText text, MarkupRegistr foreach (var markups in palette) { writer.WriteStartArray(); - foreach (var markup in markups) WriteMarkup(writer, markup, registry); + foreach (var markup in markups.Items) WriteMarkup(writer, markup, registry); writer.WriteEndArray(); } writer.WriteEndArray(); diff --git a/MarkupString/PublicAPI.Unshipped.txt b/MarkupString/PublicAPI.Unshipped.txt index 54795e9..7cd9d0e 100644 --- a/MarkupString/PublicAPI.Unshipped.txt +++ b/MarkupString/PublicAPI.Unshipped.txt @@ -878,3 +878,5 @@ override MarkupString.ElementMarkup.ToString() -> string! static MarkupString.ElementMarkup.operator !=(MarkupString.ElementMarkup? left, MarkupString.ElementMarkup? right) -> bool static MarkupString.ElementMarkup.operator ==(MarkupString.ElementMarkup? left, MarkupString.ElementMarkup? right) -> bool 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![]!