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
This commit is contained in:
Kamron Batman 2026-03-22 14:23:44 -07:00 • committed by GitHub
parent 9f39198fab
commit 61e41df00c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
38 changed files with 846 additions and 200 deletions

View file

@ -210,15 +210,6 @@ public ref struct ValueStringBuilder
}
}
// Compiler generated
public void Append(ref RawInterpolatedStringHandler handler) => Append(handler.Text);
// Compiler generated
public void Append(
IFormatProvider? formatProvider,
[InterpolatedStringHandlerArgument("formatProvider")]
ref RawInterpolatedStringHandler handler
) => Append(handler.Text);
[MethodImpl(MethodImplOptions.AggressiveInlining)]
@ -463,4 +454,128 @@ public ref struct ValueStringBuilder
_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(' ');
}
}
}
}

View file

@ -210,7 +210,7 @@ public class ClientVersion : IComparable<ClientVersion>, IComparer<ClientVersion
private string ToStringImpl()
{
using var builder = ValueStringBuilder.Create();
using var builder = new ValueStringBuilder(stackalloc char[32]);
if (Type == ClientType.SA)
{

View file

@ -51,7 +51,7 @@ public class LocalizationEntry
private static void ParseText(string text, out string[] textSlices, out string stringFormatter)
{
var sb = ValueStringBuilder.Create(256);
using var sb = ValueStringBuilder.Create(256);
using var queue = PooledRefQueue<string>.Create();
var hasMatch = false;
@ -81,8 +81,6 @@ public class LocalizationEntry
textSlices = queue.ToArray();
stringFormatter = hasMatch ? sb.ToString() : null;
sb.Dispose();
}
/// <summary>

View file

@ -42,7 +42,7 @@ public static class MapSelection
public static string ToCommaDelimitedString(this MapSelectionFlags flags)
{
using var builder = ValueStringBuilder.Create();
using var builder = new ValueStringBuilder(stackalloc char[160]);
foreach (var flag in flags.GetEnumerable())
{

View file

@ -20,21 +20,21 @@ namespace Server.Text;
public interface ISelfInterpolatedStringHandler
{
public void Add([InterpolatedStringHandlerArgument("")] ref InterpolatedStringHandler handler);
public void InitializeInterpolation(int literalLength, int formattedCount);
public void AppendLiteral(string value);
public void AppendFormatted<T>(T value);
public void AppendFormatted<T>(T value, string? format);
public void AppendFormatted<T>(T value, int alignment);
public void AppendFormatted<T>(T value, int alignment, string? format);
public void AppendFormatted(ReadOnlySpan<char> value);
public void AppendFormatted(ReadOnlySpan<char> value, int alignment, string? format = null);
public void AppendFormatted(object? value, int alignment = 0, string? format = null);
public void AppendFormatted(string? value);
public void AppendFormatted(string? value, int alignment, string? format = null);
void Add([InterpolatedStringHandlerArgument("")] ref InterpolatedStringHandler handler);
void InitializeInterpolation(int literalLength, int formattedCount);
void AppendLiteral(string value);
void AppendFormatted<T>(T value);
void AppendFormatted<T>(T value, string? format);
void AppendFormatted<T>(T value, int alignment);
void AppendFormatted<T>(T value, int alignment, string? format);
void AppendFormatted(ReadOnlySpan<char> value);
void AppendFormatted(ReadOnlySpan<char> value, int alignment, string? format = null);
void AppendFormatted(object? value, int alignment = 0, string? format = null);
void AppendFormatted(string? value);
void AppendFormatted(string? value, int alignment, string? format = null);
[InterpolatedStringHandler]
public ref struct InterpolatedStringHandler
ref struct InterpolatedStringHandler
{
private ISelfInterpolatedStringHandler _parent;