ModernUO/Projects/Server/Buffers/ValueStringBuilder.cs
Kamron Batman 61e41df00c
feat: Add zero-alloc interpolation handler to ValueStringBuilder, replace all StringBuilder usage (#2387)
## Summary

- **Add a self-referencing `InterpolationHandler` to `ValueStringBuilder`** that writes directly into the builder's buffer — zero intermediate allocation, works with `stackalloc`-backed builders
- **Replace all `System.Text.StringBuilder` usage** across the codebase with `ValueStringBuilder`
- **Convert `ValueStringBuilder.Create()` to `stackalloc`** at 10 sites where output length is provably bounded
- **Convert manual `Dispose()` to `using var`** where possible, and hoist loop-scoped builders outside loops with `Reset()`
- **Convert verbose `Append()` chains to `Append($"...")`** interpolation for readability
- **Add comprehensive documentation** for string handling patterns

## InterpolationHandler Design

`ValueStringBuilder` is a `ref struct`, which creates challenges for C#'s interpolated string handler pattern:

- **`ref` fields to ref structs are not allowed** (CS9050)
- **`[InterpolatedStringHandlerArgument("")]` passes struct receivers by value**, not by ref
- **`ISelfInterpolatedStringHandler` requires boxing** ref structs into interface fields

**Solution: Copy-and-reconcile pattern.** The handler receives a value copy of the builder. The copy shares the same underlying `char` buffer (`Span` points to the same `stackalloc`/pooled memory), so writes go to the original buffer. `Append()` reconciles by `this = handler._builder`, updating `_length` and any buffer references changed by `Grow()`.

This is safe because:
- The game loop is single-threaded — no concurrent access between handler construction and reconciliation
- If `Grow()` occurs in the copy, the original's stale buffer isn't accessed until `Append()` replaces it
- `Dispose()` correctly returns the reconciled buffer to the pool

## Changes by Category

### ValueStringBuilder (`Projects/Server/Buffers/ValueStringBuilder.cs`)
- Added nested `InterpolationHandler` ref struct with copy-and-reconcile pattern
- Added `Append([InterpolatedStringHandlerArgument("")] scoped ref InterpolationHandler)` method
- Removed `RawInterpolatedStringHandler` overloads (new handler replaces them)
- All `AppendFormatted` overloads delegate to existing `Append` methods (no code duplication)
- Alignment support via direct private field access (nested type privilege)

### StringBuilder → ValueStringBuilder (15 files)
Replaced all `new StringBuilder()` with `ValueStringBuilder.Create()` or `stackalloc`:
- ConPVP games: KingOfTheHill, DoubleDom, CTF, BombingRun, TourneyMatch
- ConPVP infrastructure: Tournament, Participant, TourneyParticipant
- ConPVP gumps: ArenaGump, TournamentBracketGump, AcceptTeamGump, ConfirmSignupGump
- Commands: Handlers, Logging, Add
- Other: TownCrier, SpeechLogGump, TestCenter

Key patterns:
- `sb = new StringBuilder()` reassignment → `sb.Reset()`
- `sb.AppendFormat("{0:N0}", value)` → `sb.Append($"{value:N0}")`
- `sb.Append(x).Append(y)` chains → separate statements (VSB returns void)

### Create() → stackalloc (10 files)
Converted heap-allocated builders to stackalloc where output is bounded:
- ClientVersion (32), MapSelection (160), HouseRaffleStone (48)
- HolySense (96), UnholySense (96), ClientVerification (192)
- AcceptTeamGump (64), ConfirmSignupGump (64)
- BaseWeapon (160), BaseArmor (128)

### Loop optimizations (2 files)
Hoisted `ValueStringBuilder` creation outside loops with `Reset()` per iteration:
- TourneyMatch.cs: `using var` inside for loop → stackalloc before loop
- ArenaGump.cs: `Create()` + `Dispose()` per iteration → stackalloc before loop

### Append chain → interpolation (5 files)
Converted multi-line `Append()` chains to `Append($"...")`:
- BountyMessage.cs: title switch (6 cases), paragraph (15→1 Append), description lines, closing
- AcceptTeamGump, ConfirmSignupGump, TournamentBracketGump: tournament type strings
- AdminGump: comment/tag formatting in loops

### Documentation
- `dev-docs/string-handling.md`: Full reference — construction, interpolation, disposal, decision guide
- `dev-docs/claude-skills/modernuo-string-handling.md`: Claude skill with quick reference
- `CLAUDE.md`: Added rule 17 (no StringBuilder), dev-docs table entry, skills table entry
- `dev-docs/code-standards.md`: Updated memory management section

## Test Plan

- [x] `dotnet build` — 0 errors, 0 warnings
- [x] `dotnet test` — 940/940 tests pass
- [x] 28 ValueStringBuilder tests covering all reconciliation scenarios:
  - Stackalloc no-grow, stackalloc with grow (→pool transition)
  - Heap no-grow, heap with grow, heap double grow
  - Pre-existing content with and without grow
  - Sequential multiple `Append($"...")` calls
  - Mixed plain + interpolated Append
  - Empty interpolation, literal-only, format specifiers
  - Null string holes, ISpanFormattable types
  - Dispose after stackalloc→pool grow
2026-03-22 14:23:44 -07:00

581 lines
17 KiB
C#

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#nullable enable
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Server.Buffers;
namespace Server.Text;
public ref struct ValueStringBuilder
{
private char[] _arrayToReturnToPool;
private Span<char> _chars;
private int _length;
private bool _mt;
private ArrayPool<char> ArrayPool
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => _mt ? ArrayPool<char>.Shared : STArrayPool<char>.Shared;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ValueStringBuilder Create(int capacity = 64, bool mt = false) => new(capacity, mt);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static ValueStringBuilder CreateMT(int capacity = 64) => new(capacity, true);
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(ReadOnlySpan<char> initialString, bool mt = false) : this(initialString.Length, mt)
{
Append(initialString);
}
public ValueStringBuilder(ReadOnlySpan<char> initialString, Span<char> initialBuffer, bool mt = false) : this(initialBuffer, mt)
{
Append(initialString);
}
public ValueStringBuilder(Span<char> initialBuffer, bool mt = false)
{
_mt = mt;
_arrayToReturnToPool = null;
_chars = initialBuffer;
_length = 0;
}
// If this ctor is used, you cannot pass in stackalloc ROS for append/replace.
public ValueStringBuilder(int initialCapacity, bool mt = false)
{
_mt = mt;
_length = 0;
_arrayToReturnToPool = (_mt ? ArrayPool<char>.Shared : STArrayPool<char>.Shared).Rent(initialCapacity);
_chars = _arrayToReturnToPool;
}
public int Length => _length;
public int Capacity => _chars.Length;
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Reset()
{
_length = 0;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void EnsureCapacity(int capacity)
{
if (capacity > _chars.Length)
{
Grow(capacity - Length);
}
}
/// <summary>
/// Get a pinnable reference to the builder.
/// Does not ensure there is a null char after <see cref="Length"/>
/// This overload is pattern matched in the C# 7.3+ compiler so you can omit
/// the explicit method call, and write eg "fixed (char* c = builder)"
/// </summary>
public ref char GetPinnableReference() => ref MemoryMarshal.GetReference(_chars);
/// <summary>
/// Get a pinnable reference to the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ref char GetPinnableReference(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return ref MemoryMarshal.GetReference(_chars);
}
public ref char this[int index] => ref _chars[index];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public override string ToString() => _chars[.._length].ToString();
/// <summary>Returns the underlying storage of the builder.</summary>
public Span<char> RawChars => _chars;
/// <summary>
/// Returns a span around the contents of the builder.
/// </summary>
/// <param name="terminate">Ensures that the builder has a null char after <see cref="Length"/></param>
public ReadOnlySpan<char> AsSpan(bool terminate)
{
if (terminate)
{
EnsureCapacity(_length + 1);
_chars[_length] = '\0';
}
return _chars[.._length];
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan() => _chars[.._length];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start) => _chars[start..];
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public ReadOnlySpan<char> AsSpan(int start, int length) => _chars.Slice(start, length);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool TryCopyTo(Span<char> destination, out int charsWritten)
{
if (_chars[.._length].TryCopyTo(destination))
{
charsWritten = _length;
return true;
}
charsWritten = 0;
return false;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, char value, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
var remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
_chars.Slice(index, count).Fill(value);
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Insert(int index, string? s)
{
if (s == null)
{
return;
}
var count = s.Length;
if (_length > _chars.Length - count)
{
Grow(count);
}
var remaining = _length - index;
_chars.Slice(index, remaining).CopyTo(_chars[(index + count)..]);
s.AsSpan().CopyTo(_chars[index..]);
_length += count;
}
public void Append<T>(T value, string? format = null)
{
if (value is IFormattable)
{
if (value is ISpanFormattable)
{
var destination = _chars[_length..];
int charsWritten;
while (!((ISpanFormattable)value).TryFormat(destination, out charsWritten, format, default))
{
Grow(1);
destination = _chars[_length..];
}
if ((uint)charsWritten > (uint)destination.Length)
{
throw new FormatException("Invalid string");
}
_length += charsWritten;
}
else
{
Append(((IFormattable)value).ToString(format, default)); // constrained call avoiding boxing for value types
}
}
else if (value is not null)
{
Append(value.ToString());
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(string? s)
{
if (s == null)
{
return;
}
var pos = _length;
if (s.Length == 1 && (uint)pos < (uint)_chars.Length) // very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
{
_chars[pos] = s[0];
_length = pos + 1;
}
else
{
AppendSlow(s);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void AppendLine(string? s)
{
if (s == null)
{
return;
}
// very common case, e.g. appending strings from NumberFormatInfo like separators, percent symbols, etc.
if (s.Length == 1)
{
Append(s[0]);
}
else
{
AppendSlow(s);
}
Append(Environment.NewLine);
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
private void AppendSlow(string? s)
{
var pos = _length;
if (pos > _chars.Length - s.Length)
{
Grow(s.Length);
}
s.AsSpan().CopyTo(_chars[pos..]);
_length += s.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(char c, int count)
{
if (_length > _chars.Length - count)
{
Grow(count);
}
var dst = _chars.Slice(_length, count);
for (var i = 0; i < dst.Length; i++)
{
dst[i] = c;
}
_length += count;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe void Append(char* value, int length)
{
var pos = _length;
if (pos > _chars.Length - length)
{
Grow(length);
}
var dst = _chars.Slice(_length, length);
for (var i = 0; i < dst.Length; i++)
{
dst[i] = *value++;
}
_length += length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Append(scoped ReadOnlySpan<char> value)
{
var pos = _length;
if (pos > _chars.Length - value.Length)
{
Grow(value.Length);
}
value.CopyTo(_chars[_length..]);
_length += value.Length;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public Span<char> AppendSpan(int length)
{
var origPos = _length;
if (origPos > _chars.Length - length)
{
Grow(length);
}
_length = origPos + length;
return _chars.Slice(origPos, length);
}
/// <summary>
/// Resize the internal buffer either by doubling current buffer size or
/// by adding <paramref name="additionalCapacityBeyondPos"/> to
/// <see cref="Length"/> whichever is greater.
/// </summary>
/// <param name="additionalCapacityBeyondPos">
/// Number of chars requested beyond current position.
/// </param>
[MethodImpl(MethodImplOptions.NoInlining)]
private void Grow(int additionalCapacityBeyondPos)
{
var poolArray = ArrayPool.Rent(Math.Max(_length + additionalCapacityBeyondPos, _chars.Length * 2));
_chars[.._length].CopyTo(poolArray);
var toReturn = _arrayToReturnToPool;
_chars = _arrayToReturnToPool = poolArray;
if (toReturn != null)
{
ArrayPool.Return(toReturn);
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Dispose()
{
if (_arrayToReturnToPool != null)
{
ArrayPool.Return(_arrayToReturnToPool);
}
this = default; // for safety, to avoid using pooled array if this instance is erroneously appended to again
}
#nullable restore
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void ReplaceAny(ReadOnlySpan<char> oldChars, ReadOnlySpan<char> newChars, int startIndex, int count)
{
var currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOfAny(oldChars);
if (indexOf == -1)
{
break;
}
var chr = slice[indexOf];
slice[indexOf] = newChars[oldChars.IndexOf(chr)];
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Replace(char oldChar, char newChar, int startIndex, int count)
{
var currentLength = _length;
if ((uint)startIndex > (uint)currentLength)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (count < 0 || startIndex > currentLength - count)
{
throw new ArgumentOutOfRangeException(nameof(count));
}
var slice = _chars;
while (true)
{
var indexOf = slice.IndexOf(oldChar);
if (indexOf == -1)
{
break;
}
slice[indexOf] = newChar;
slice = slice[(indexOf + 1)..];
}
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public void Remove(int startIndex, int length)
{
if (length < 0)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex < 0)
{
throw new ArgumentOutOfRangeException(nameof(startIndex));
}
if (length > _length - startIndex)
{
throw new ArgumentOutOfRangeException(nameof(length));
}
if (startIndex == 0)
{
_chars = _chars[length..];
}
else if (startIndex + length == _length)
{
_chars = _chars[..startIndex];
}
else
{
// Somewhere in the middle, this will be slow
_chars[(startIndex + length)..].CopyTo(_chars[startIndex..]);
}
_length -= length;
}
// Copy-and-reconcile interpolation handler.
// The handler receives a VALUE COPY of the builder (C# limitation: [InterpolatedStringHandlerArgument("")]
// passes struct receivers by value). The copy shares the same underlying char buffer (Span points to
// the same stackalloc/pooled memory), so writes go to the original buffer. If Grow() happens, the copy
// gets a new buffer. Append() reconciles by copying the handler's state back to the original.
// Safe because the game loop is single-threaded — no concurrent access between handler construction
// and reconciliation.
public void Append(
[InterpolatedStringHandlerArgument("")]
scoped ref InterpolationHandler handler)
{
// Reconcile: the handler's copy has the updated _length (and possibly new buffer from Grow).
this = handler._builder;
}
[InterpolatedStringHandler]
public ref struct InterpolationHandler
{
internal ValueStringBuilder _builder;
public InterpolationHandler(int literalLength, int formattedCount, ValueStringBuilder builder)
{
_builder = builder;
_builder.EnsureCapacity(_builder._length + literalLength + formattedCount * 11);
}
public void AppendLiteral(string value) => _builder.Append(value);
public void AppendFormatted<T>(T value) => _builder.Append(value);
public void AppendFormatted<T>(T value, string? format) => _builder.Append(value, format);
public void AppendFormatted<T>(T value, int alignment)
{
var startingPos = _builder._length;
_builder.Append(value);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
public void AppendFormatted<T>(T value, int alignment, string? format)
{
var startingPos = _builder._length;
_builder.Append(value, format);
if (alignment != 0)
{
AppendOrInsertAlignmentIfNeeded(startingPos, alignment);
}
}
public void AppendFormatted(scoped ReadOnlySpan<char> value) => _builder.Append(value);
public void AppendFormatted(scoped ReadOnlySpan<char> value, int alignment = 0, string? format = null)
{
var leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
var paddingRequired = alignment - value.Length;
if (paddingRequired <= 0)
{
_builder.Append(value);
return;
}
_builder.EnsureCapacity(_builder._length + value.Length + paddingRequired);
if (leftAlign)
{
_builder.Append(value);
_builder.AppendSpan(paddingRequired).Fill(' ');
}
else
{
_builder.AppendSpan(paddingRequired).Fill(' ');
_builder.Append(value);
}
}
public void AppendFormatted(string? value) => _builder.Append(value);
public void AppendFormatted(string? value, int alignment = 0, string? format = null) =>
AppendFormatted<string?>(value, alignment, format);
public void AppendFormatted(object? value, int alignment = 0, string? format = null) =>
AppendFormatted<object?>(value, alignment, format);
private void AppendOrInsertAlignmentIfNeeded(int startingPos, int alignment)
{
var charsWritten = _builder._length - startingPos;
var leftAlign = false;
if (alignment < 0)
{
leftAlign = true;
alignment = -alignment;
}
var paddingNeeded = alignment - charsWritten;
if (paddingNeeded <= 0)
{
return;
}
if (leftAlign)
{
_builder.AppendSpan(paddingNeeded).Fill(' ');
}
else
{
// Shift content right, fill padding on left
_builder.AppendSpan(paddingNeeded);
_builder._chars.Slice(startingPos, charsWritten)
.CopyTo(_builder._chars[(startingPos + paddingNeeded)..]);
_builder._chars.Slice(startingPos, paddingNeeded).Fill(' ');
}
}
}
}