ModernUO/Projects/UOContent/Misc
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
..
AccountPrompt.cs fix: Fixes console clobbering when prompted to add an owner account (#2133) 2025-02-26 18:43:20 -08:00
AdminFirewall.cs fix: Fixes TCPServer accept async, makes Firewall/IP Limiter multithreaded (#2134) 2025-02-27 22:19:38 -08:00
Animations.cs fix: Moves many EventSinks out of core. (#1783) 2024-05-21 10:02:30 -07:00
AOS.cs feat: Adds PlayerDeathEvent and CreatureDeathEvent using code generated events (#1927) 2024-09-05 21:23:03 -07:00
AttackMessage.cs fix: Fixes crafter deserialize, cleans up bandages, and codegens misc items (#1350) 2023-02-25 00:54:12 -08:00
AutoRestart.cs fix: Fixes missing methods. Adds more admin gump world building (#1675) 2024-02-10 20:31:25 -08:00
Broadcasts.cs Fixes exiting/crash handling/ctrl+c (#237) 2020-09-12 00:05:38 -07:00
Cleanup.cs fix: Fixes structured logging (#1043) 2022-06-05 01:00:22 -07:00
ClientVerification.cs feat: Add zero-alloc interpolation handler to ValueStringBuilder, replace all StringBuilder usage (#2387) 2026-03-22 14:23:44 -07:00
CrashGuard.cs chore: Use var everywhere (#2294) 2025-12-27 16:47:28 -08:00
DispellableAttribute.cs Formats UO Content (#201) 2020-08-27 18:30:38 -07:00
DispellableFieldAttribute.cs Formats UO Content (#201) 2020-08-27 18:30:38 -07:00
DoorGenerator.cs feat: Adds wall z-offset detection for doorgen (#2025) 2024-12-17 10:40:02 -08:00
Email.cs fix: Fixes spawn entry deserialization (#1693) 2024-03-03 08:45:16 -08:00
Emitter.cs Fixes brace style (#248) 2020-09-13 21:49:46 -07:00
FoodDecay.cs feat: Moves TcpServer to another thread. Rewrites Firewall (#1660) 2024-01-20 14:25:12 -08:00
Geometry.cs chore: Cleans up pattern checks. (#892) 2021-12-24 15:53:59 -08:00
Guild.cs chore: Use var everywhere (#2294) 2025-12-27 16:47:28 -08:00
HardwareInfo.cs fix: Fixes thread guard and cleans up incoming packet reader (#1641) 2023-12-19 17:04:09 -08:00
InhumanSpeech.cs feat: Replaces params array with params ReadOnlySpan (#2125) 2025-02-13 21:19:02 -08:00
Keywords.cs feat: T2A ping-pong mechanic and consider sins behaviour (#2356) 2026-03-10 23:10:27 -07:00
LanguageStatistics.cs fix: Adds command help, webpage, and fixes issues with other commands (#1669) 2024-02-10 00:19:19 -08:00
LightCycle.cs fix: Fixes buffs don't start/stop properly. Streamlines constructor and Add/Remove buffs. (#2082) 2025-01-24 18:20:23 -08:00
LoginStats.cs feat: Converts OnLogin to a coded generated event (#2070) 2025-01-17 15:21:45 -08:00
Loot.cs feat: Replaces params array with params ReadOnlySpan (#2125) 2025-02-13 21:19:02 -08:00
LootPack.cs fix: Fixes slayer assignment (#2344) 2026-02-26 19:14:19 -08:00
MessageHelper.cs fix: Codegens rares and solen items (#1371) 2023-03-11 19:25:48 -08:00
MondainsLegacy.cs fix: Consolidates Color/Center html (#1762) 2024-05-07 23:56:32 -07:00
NameList.cs fix: Cleans up murder system (#1428) 2023-07-16 00:04:30 -07:00
NameVerification.cs fix: Fixes detecting consecutive exceptions in name validation (#2192) 2025-05-18 21:02:05 -07:00
Notoriety.cs feat: Adds Mobile.Murderer virtual property, consolidates kill-threshold checks (#2355) 2026-03-06 08:36:41 -08:00
PacketThrottles.cs chore: Use var everywhere (#2294) 2025-12-27 16:47:28 -08:00
Paperdoll.cs fix(core): Converts remaining player packets (#374) 2020-12-30 16:09:51 -08:00
Poison.cs feat: Refactor Poison system, implement Darkglow & Parasitic effects (#2385) 2026-03-21 21:27:22 -07:00
PoisonKinds.cs feat: Refactor Poison system, implement Darkglow & Parasitic effects (#2385) 2026-03-21 21:27:22 -07:00
ProfanityProtection.cs fix: Fixes and optimizes NameVerification and ProfanityProtection (#2153) 2025-04-12 02:26:10 -07:00
ProfessionInfo.cs feat: Moves network related events to UOContent using code generation (#1945) 2024-09-06 16:57:10 -07:00
Profile.cs fix: Moves many EventSinks out of core. (#1783) 2024-05-21 10:02:30 -07:00
RaceDefinitions.cs fix: Updates races to properly support gargoyle equipment. (#744) 2021-08-29 00:43:55 -07:00
RegenRates.cs fix: Fixes poison field duration, cleans up skill calculations and poison calculations (#1582) 2023-11-04 12:32:54 -07:00
RenameRequests.cs fix: Fixes and optimizes NameVerification and ProfanityProtection (#2153) 2025-04-12 02:26:10 -07:00
ResourceInfo.cs fix: Codegens BOD rewards. (#1361) 2023-03-06 19:01:14 -08:00
ServerAccess.cs fix: Reverts GetAccount to use IAccount. Adds IAccount to serialization. (#1565) 2023-10-25 19:17:57 -07:00
ServerList.cs feat: Upgrades networking to use io_uring. (#2315) 2026-02-01 16:02:32 -08:00
ShardPoller.cs feat: Adds size/style support to gump builders, optimizes EscapeHtml (#2257) 2025-11-23 11:35:31 -08:00
ShrinkTable.cs chore: Use var everywhere (#2294) 2025-12-27 16:47:28 -08:00
StaffInfo.cs fix: Codegens gifts. Unifies staff names. Thank you to the community! (#1766) 2024-05-08 20:44:00 -07:00
StaminaSystem.cs feat: Adds walk/run restriction configs (#2345) 2026-02-28 09:41:40 -08:00
Titles.cs fix: Fix Lord/Lady title display in paperdoll when fame >= 10000 (#2022) 2024-12-16 12:28:52 -08:00
ToggleItem.cs fix: Codegens house/vendors (#1767) 2024-05-08 22:45:59 -07:00
TreasureMapProtection.cs chore: Use var everywhere (#2294) 2025-12-27 16:47:28 -08:00
ValidationQueue.cs Fixes brace style (#248) 2020-09-13 21:49:46 -07:00
Weather.cs fix: Moves containers/bods/traps/etc to serialization generator (#2310) 2026-01-07 21:55:55 -08:00
WelcomeTimer.cs Removes UOAM vendors. (#241) 2020-09-12 11:56:52 -07:00