ModernUO/Projects/UOContent/Engines/ConPVP/Participant.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

284 lines
6.8 KiB
C#

using System;
using Server.Mobiles;
using Server.Text;
namespace Server.Engines.ConPVP
{
public class Participant
{
public Participant(DuelContext context, int count)
{
Context = context;
// m_Stakes = new StakesContainer( context, this );
Resize(count);
}
public int Count => Players.Length;
public DuelPlayer[] Players { get; private set; }
public DuelContext Context { get; }
public TourneyParticipant TourneyPart { get; set; }
public int FilledSlots
{
get
{
var count = 0;
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i] != null)
{
++count;
}
}
return count;
}
}
public bool HasOpenSlot
{
get
{
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i] == null)
{
return true;
}
}
return false;
}
}
public bool Eliminated
{
get
{
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i]?.Eliminated == false)
{
return false;
}
}
return true;
}
}
public string NameList
{
get
{
using var sb = ValueStringBuilder.Create(256);
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i] == null)
{
continue;
}
var mob = Players[i].Mobile;
if (sb.Length > 0)
{
sb.Append(", ");
}
sb.Append(mob.Name);
}
return sb.Length == 0 ? "Empty" : sb.ToString();
}
}
public DuelPlayer Find(Mobile mob)
{
if (mob is PlayerMobile pm)
{
if (pm.DuelContext == Context && pm.DuelPlayer.Participant == this)
{
return pm.DuelPlayer;
}
return null;
}
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i]?.Mobile == mob)
{
return Players[i];
}
}
return null;
}
public bool Contains(Mobile mob) => Find(mob) != null;
public void Broadcast(int hue, string message, string nonLocalOverhead, string localOverhead)
{
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i] != null)
{
if (message != null)
{
Players[i].Mobile.SendMessage(hue, message);
}
if (nonLocalOverhead != null)
{
Players[i]
.Mobile.NonlocalOverheadMessage(
MessageType.Regular,
hue,
false,
string.Format(
nonLocalOverhead,
Players[i].Mobile.Name,
Players[i].Mobile.Female ? "her" : "his"
)
);
}
if (localOverhead != null)
{
Players[i].Mobile.LocalOverheadMessage(MessageType.Regular, hue, false, localOverhead);
}
}
}
}
public void Nullify(DuelPlayer player)
{
if (player == null)
{
return;
}
var index = Array.IndexOf(Players, player);
if (index == -1)
{
return;
}
Players[index] = null;
}
public void Remove(DuelPlayer player)
{
if (player == null)
{
return;
}
var index = Array.IndexOf(Players, player);
if (index == -1)
{
return;
}
var old = Players;
Players = new DuelPlayer[old.Length - 1];
for (var i = 0; i < index; ++i)
{
Players[i] = old[i];
}
for (var i = index + 1; i < old.Length; ++i)
{
Players[i - 1] = old[i];
}
}
public void Remove(Mobile player)
{
Remove(Find(player));
}
public void Add(Mobile player)
{
if (Contains(player))
{
return;
}
for (var i = 0; i < Players.Length; ++i)
{
if (Players[i] == null)
{
Players[i] = new DuelPlayer(player, this);
return;
}
}
Resize(Players.Length + 1);
Players[^1] = new DuelPlayer(player, this);
}
public void Resize(int count)
{
var old = Players;
Players = new DuelPlayer[count];
if (old != null)
{
var ct = 0;
for (var i = 0; i < old.Length; ++i)
{
if (old[i] != null && ct < count)
{
Players[ct++] = old[i];
}
}
}
}
}
public class DuelPlayer
{
private bool m_Eliminated;
public DuelPlayer(Mobile mob, Participant p)
{
Mobile = mob;
Participant = p;
if (mob is PlayerMobile mobile)
{
mobile.DuelPlayer = this;
}
}
public Mobile Mobile { get; }
public bool Ready { get; set; }
public bool Eliminated
{
get => m_Eliminated;
set
{
m_Eliminated = value;
if (Participant.Context.m_Tournament != null && m_Eliminated)
{
Participant.Context.m_Tournament.OnEliminated(this);
Mobile.SendEverything();
}
}
}
public Participant Participant { get; set; }
}
}