## 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
133 lines
3.6 KiB
Markdown
133 lines
3.6 KiB
Markdown
# ModernUO String Handling Skill
|
|
|
|
## When This Skill Applies
|
|
- Any code that builds strings dynamically (concatenation, formatting, interpolation)
|
|
- Converting `System.Text.StringBuilder` to `ValueStringBuilder`
|
|
- Packet string construction
|
|
- Gump/message text building
|
|
|
|
## Core Rule
|
|
**Never use `System.Text.StringBuilder`**. Use `Server.Text.ValueStringBuilder` everywhere.
|
|
|
|
## Quick Reference
|
|
|
|
### Construction
|
|
```csharp
|
|
// Bounded output (preferred): zero heap allocation
|
|
using var sb = new ValueStringBuilder(stackalloc char[128]);
|
|
|
|
// Unbounded output: rents from STArrayPool
|
|
using var sb = ValueStringBuilder.Create(256);
|
|
using var sb = ValueStringBuilder.Create(); // default 64 chars
|
|
```
|
|
|
|
### String Interpolation
|
|
Works with stackalloc — writes directly into the builder's buffer:
|
|
```csharp
|
|
using var sb = new ValueStringBuilder(stackalloc char[64]);
|
|
sb.Append($"Player {name} has {kills} kills");
|
|
```
|
|
|
|
### Reuse via Reset
|
|
Use `Reset()` instead of creating a new builder:
|
|
```csharp
|
|
using var sb = new ValueStringBuilder(stackalloc char[128]);
|
|
foreach (var item in items)
|
|
{
|
|
sb.Reset();
|
|
sb.Append($"{item.Name}: {item.Value}");
|
|
Process(sb.ToString());
|
|
}
|
|
```
|
|
|
|
### Reading Results
|
|
- `sb.ToString()` — when you need a string (allocates)
|
|
- `sb.AsSpan()` — when consumer accepts `ReadOnlySpan<char>` (zero-alloc)
|
|
|
|
## Common Mistakes
|
|
|
|
### 1. Using StringBuilder
|
|
```csharp
|
|
// BAD
|
|
var sb = new StringBuilder();
|
|
sb.Append(name);
|
|
return sb.ToString();
|
|
|
|
// GOOD
|
|
using var sb = new ValueStringBuilder(stackalloc char[64]);
|
|
sb.Append(name);
|
|
return sb.ToString();
|
|
```
|
|
|
|
### 2. Forgetting `using var`
|
|
```csharp
|
|
// BAD: pooled array may leak if Grow() happened
|
|
var sb = ValueStringBuilder.Create();
|
|
return sb.ToString(); // never disposed!
|
|
|
|
// GOOD
|
|
using var sb = ValueStringBuilder.Create();
|
|
return sb.ToString();
|
|
```
|
|
|
|
### 3. Chaining Append calls
|
|
```csharp
|
|
// BAD: VSB Append returns void, not this
|
|
sb.Append("a").Append("b");
|
|
|
|
// GOOD
|
|
sb.Append("a");
|
|
sb.Append("b");
|
|
|
|
// BETTER: use interpolation
|
|
sb.Append($"a{value}b");
|
|
```
|
|
|
|
### 4. Reassigning a using variable
|
|
```csharp
|
|
// BAD: can't reassign using var
|
|
using var sb = ValueStringBuilder.Create();
|
|
sb = ValueStringBuilder.Create(); // CS1656!
|
|
|
|
// GOOD: use Reset()
|
|
using var sb = ValueStringBuilder.Create();
|
|
sb.Reset();
|
|
```
|
|
|
|
### 5. `using var` with `ref` extension methods
|
|
```csharp
|
|
// BAD: CS1657 — using var can't be passed by ref
|
|
using var sb = new ValueStringBuilder(stackalloc char[64]);
|
|
sb.AppendSpaceWithArticle(text, articleAn); // takes ref VSB
|
|
|
|
// GOOD: manual Dispose
|
|
var sb = new ValueStringBuilder(stackalloc char[64]);
|
|
sb.AppendSpaceWithArticle(text, articleAn);
|
|
var result = sb.ToString();
|
|
sb.Dispose();
|
|
```
|
|
|
|
### 6. No AppendFormat — use `$"..."` interpolation
|
|
```csharp
|
|
// BAD: AppendFormat doesn't exist on VSB (no object[] params equivalent)
|
|
sb.AppendFormat("{0:N0} points, {1:N0} kills", score, kills);
|
|
|
|
// GOOD: use interpolation with format specifiers (zero boxing, zero intermediate strings)
|
|
sb.Append($"{score:N0} points, {kills:N0} kills");
|
|
```
|
|
|
|
## Capacity Sizing Guide
|
|
|
|
| Content | Recommended |
|
|
|---|---|
|
|
| Version strings, coordinates | `stackalloc char[32-48]` |
|
|
| Player names, short messages | `stackalloc char[64]` |
|
|
| Item descriptions, titles | `stackalloc char[128]` |
|
|
| Paragraph text, HTML snippets | `stackalloc char[256]` |
|
|
| Large HTML, gump content | `Create(512)` or `Create()` |
|
|
| Unbounded (logs, file paths) | `Create()` |
|
|
|
|
## Related Docs
|
|
- `dev-docs/string-handling.md` — full reference
|
|
- `dev-docs/code-standards.md` — memory management rules
|
|
- `dev-docs/property-lists.md` — IPropertyList string interpolation (different handler)
|