SOURCE DUMP v1

This commit is contained in:
Rian Drake 2026-10-15 14:09:11 +13:00
commit fb20299e9d
8 changed files with 768360 additions and 0 deletions

View file

@ -0,0 +1,194 @@
#define IMPLEMENT_STRING_BUILDER
using System.Buffers;
namespace Brutal.Strings;
#if IMPLEMENT_STRING_BUILDER
public partial class StringBuilder<TChar>
#else
public partial struct ValueStringBuilder<TChar>
#endif
{
private Span<TChar> GetSpan(int contentSizeHint, int alignment)
{
return GetSpan(Math.Max(contentSizeHint, Math.Abs(alignment)));
}
private void Align(Span<TChar> destination, ref int elementsWritten, int alignment)
{
if (alignment == 0)
return;
// Alignment is based on grapheme count, which means we may write more than "alignment",
// i.e. more than we pre-grew for - retry until it fits.
while (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
destination = GetSpan(destination.Length + 1);
}
/// Pads content already written and advanced since <paramref name="start"/> to <paramref name="alignment"/>,
/// growing as needed. Used by nested interpolation: the inner handler writes through directly, then the outer
/// hole's alignment is applied after the fact. <paramref name="start"/> is the position before the inner wrote.
public void AlignFrom(int start, int alignment)
{
if (alignment == 0)
return;
// rewind - don't use MoveTo() as it would null-terminate over its first element
var elementsWritten = _position - start;
_position = start;
Align(FreeSpan, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <summary>Format <paramref name="value"/> into <typeparamref name="TChar"/> elements and append it; the writer grows as needed.</summary>
/// <param name="value">Value to format and append.</param>
/// <param name="alignment">If non-zero, pads the appended content to this many elements (positive: right-align, negative: left-align).</param>
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
/// <param name="provider">Optional format provider.</param>
/// <exception cref="ArgumentOutOfRangeException">The writer's <see cref="IBufferWriter{T}.GetSpan"/> couldn't satisfy the request (e.g. fixed-capacity writer hit its limit).</exception>
public void Append<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
var sizeHint = Math.Abs(alignment);
Span<TChar> destination;
int elementsWritten;
while (!Utf<TChar>.TryFormat(value, destination = GetSpan(sizeHint), out elementsWritten, format, provider))
{
// Format didn't fit - ask for strictly more than what we just got (progress guarantee).
sizeHint = destination.Length + 1;
}
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <summary>Tries to format <paramref name="value"/> into <typeparamref name="TChar"/> elements and append it.</summary>
/// <param name="value">The value to format and append.</param>
/// <param name="alignment">If non-zero, pads the appended content to this many elements (positive: right-align, negative: left-align).</param>
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
/// <param name="provider">Optional format provider.</param>
/// <returns>true on success; false if remaining capacity was insufficient.</returns>
public bool TryAppend<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
if (!TryGetSpan(0, alignment, out var destination))
return false;
if (!Utf<TChar>.TryFormat(value, destination, out var elementsWritten, format, provider))
return Fail(); // can't fit formatted value
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
#region string/ref struct specializations
/// <inheritdoc cref="Append{T}(T, int, string?, IFormatProvider?)" />
public void Append(String8View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
var destination = GetSpan(elementsWritten, alignment); // grow if needed / throw if doesn't fit
Utf<TChar>.GetElements(value, destination);
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <inheritdoc cref="Append{T}(T, int, string?, IFormatProvider?)" />
public void Append(String16View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
var destination = GetSpan(elementsWritten, alignment); // grow if needed / throw if doesn't fit
Utf<TChar>.GetElements(value, destination);
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <inheritdoc cref="TryAppend{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppend(String8View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
if (!TryGetSpan(elementsWritten, alignment, out var destination))
return false;
Utf<TChar>.GetElements(value, destination);
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
/// <inheritdoc cref="TryAppend{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppend(String16View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
if (!TryGetSpan(elementsWritten, alignment, out var destination))
return false;
Utf<TChar>.GetElements(value, destination);
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
#endregion
#region AppendLine
/// <summary>Append a <see cref="NewLine"/>, growing as needed.</summary>
/// <exception cref="ArgumentOutOfRangeException">The required capacity exceeds the builder's limit.</exception>
public void AppendLine() => Append(NewLine);
/// <summary>Appends <paramref name="value"/> (optionally padded) followed by <see cref="NewLine"/>, growing as needed.</summary>
/// <inheritdoc cref="AppendLine()" path="/exception"/>
public void AppendLine<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
Append(value, alignment, format, provider);
AppendLine();
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public void AppendLine(String8View value, int alignment = 0)
{
Append(value, alignment);
AppendLine();
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public void AppendLine(String16View value, int alignment = 0)
{
Append(value, alignment);
AppendLine();
}
/// Tries to append a <see cref="NewLine"/>.
public bool TryAppendLine() => TryAppend((String16View)NewLine);
/// Tries to append <paramref name="value"/> (optionally padded) followed by <see cref="NewLine"/>.
/// Rolls back atomically on failure.
public bool TryAppendLine<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
var checkpoint = _position;
if (TryAppend(value, alignment, format, provider) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppendLine(String8View value, int alignment = 0)
{
var checkpoint = _position;
if (TryAppend(value, alignment) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppendLine(String16View value, int alignment = 0)
{
var checkpoint = _position;
if (TryAppend(value, alignment) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
#endregion
}

View file

@ -0,0 +1,81 @@
namespace Brutal.Strings;
public partial class StringBuilder<TChar>
{
/// Appends an interpolated string.
public void Append([InterpolatedStringHandlerArgument("")] ref Interpolator handler)
{
// No-op: the handler writes directly into this builder as it is constructed,
// so by the time this method runs, the content is already appended.
}
/// Appends an interpolated string followed by <see cref="NewLine"/>.
public void AppendLine([InterpolatedStringHandlerArgument("")] ref Interpolator handler)
{
// Interpolated content already appended during handler construction; only add the newline.
AppendLine();
}
/// <summary>
/// Interpolated-string handler for <see cref="StringBuilder{TChar}"/>.
/// Not intended for direct use.
/// </summary>
/// <remarks>
/// Lean by design:
/// - Value-type holes flow through the generic <c>AppendFormatted&lt;T&gt;</c> kitchen-sink via <see cref="Utf{TChar}.TryFormat"/>.
/// - Char-span and byte-span holes need explicit overloads (ref structs can't flow through generic <c>T</c>).
/// - String holes are fast-tracked to avoid the kitchen-sink
/// - Nested holes (<c>$"outer {$"inner"}"</c>) write through into the same builder, zero-alloc - no temp string.
/// </remarks>
[InterpolatedStringHandler, EditorBrowsable(EditorBrowsableState.Never)]
public readonly ref struct Interpolator
{
private readonly StringBuilder<TChar> _sb;
public Interpolator(int literalLength, int formattedCount, StringBuilder<TChar> sb)
{
_sb = sb;
}
public void AppendLiteral(String16 value) => _sb.Append((String16View)value);
public void AppendFormatted<T>(T value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment, format);
// ref-struct holes can't flow through AppendFormatted<T> (no `allows ref struct`).
public void AppendFormatted(String8View value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment);
public void AppendFormatted(String16View value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment);
public void AppendFormatted(String16? value, int alignment = 0, String16? format = null) =>
_sb.Append((String16View)value, alignment);
#region nested interpolation
/// Builder position captured at construction; only used for nested interpolation alignment.
private readonly int _start;
/// Nested interpolation ctor for <see cref="AppendFormatted(Interpolator, int, String16?)"/>
public Interpolator(int literalLength, int formattedCount, Interpolator parent)
: this(literalLength, formattedCount, parent._sb)
{
_start = parent._sb._position;
}
// Nested interpolation overload
public void AppendFormatted(
[InterpolatedStringHandlerArgument("")] Interpolator nested,
int alignment = 0,
String16? format = null
)
{
// Nested hole writes into our own _sb, so by the time control returns here, `nested` has already appended.
// The only thing left to do is potentially aligning.
_sb.AlignFrom(nested._start, alignment);
}
#endregion
}
}

View file

@ -0,0 +1,215 @@
using System.Buffers;
using System.Numerics;
namespace Brutal.Strings;
using static StringBuilderUtility;
/// <summary>
/// A mutable sequence of UTF-8 or UTF-16 code units (depending on <typeparamref name="TChar"/>) with a
/// growable, null-terminated buffer and optional <see cref="MaxCapacity"/> limit. Supports C# interpolated
/// string handlers via <see cref="Interpolator"/>.
/// </summary>
/// <remarks>
/// There is deliberately no implicit conversion to <see cref="Span{T}"/>/<see cref="ReadOnlySpan{T}"/>:
/// call <see cref="WrittenSpan"/> so the borrow is visible at the call site. A span into the buffer is a
/// borrow, not a copy - span lifetime and safety are the caller's concern.
/// </remarks>
public partial class StringBuilder<TChar> : IUtf8SpanFormattable, ISpanFormattable
where TChar : unmanaged, IBinaryInteger<TChar> // IUtfChar<TChar> would be perfect, but is internal
{
/// Initializes a new instance of <see cref="StringBuilder{TChar}"/>.
/// <remarks>The output span is always null-terminated. The null terminator is not included in the capacity.</remarks>
/// <param name="capacity">Initial capacity. Must be positive.</param>
/// <param name="maxCapacity">Maximum capacity. Defaults to <see cref="Array.MaxLength"/> - 1.</param>
/// <exception cref="ArgumentOutOfRangeException"><paramref name="capacity"/> is not positive.</exception>
/// <exception cref="ArgumentException"><paramref name="maxCapacity"/> is less than <paramref name="capacity"/> or exceeds <see cref="Array.MaxLength"/> - 1.</exception>
public StringBuilder(int capacity = 64, int maxCapacity = ArrayMaxUsableLength)
{
if (capacity <= 0)
throw new ArgumentOutOfRangeException(nameof(capacity), "Capacity must be positive.");
if (maxCapacity < capacity)
throw new ArgumentException("Max capacity cannot be less than capacity.", nameof(maxCapacity));
if (maxCapacity > ArrayMaxUsableLength)
throw new ArgumentException("Max capacity cannot exceed (Array.MaxLength - 1).", nameof(maxCapacity));
_storage = new TChar[capacity + 1]; // +1 for null terminator - hidden from callers
MaxCapacity = maxCapacity;
}
/// for pooling
internal void ResetToDefault()
{
Clear();
NewLine = Environment.NewLine;
// Capacity is not reset to default - the price to pay for using a pooled instance.
// MaxCapacity isn't configurable in pooled instances.
}
#region storage
private TChar[] _storage;
/// Gets the current capacity.
public int Capacity => _storage.Length - 1;
/// Gets the maximum capacity this instance can grow to.
public readonly int MaxCapacity;
private void Resize(long newCapacity)
{
Array.Resize(ref _storage, (int)Math.Min(newCapacity, MaxCapacity) + 1); // +1 for null terminator
}
/// Doubles capacity until <paramref name="appendCount"/> more elements fit.
/// <exception cref="ArgumentOutOfRangeException">Required capacity exceeds <see cref="MaxCapacity"/>.</exception>
private void GrowBy(int appendCount)
{
var requiredCapacity = (long)_position + appendCount;
if (requiredCapacity > MaxCapacity)
throw new ArgumentOutOfRangeException(nameof(MaxCapacity), "Cannot grow beyond MaxCapacity.");
// keep doubling capacity until it's at least requiredCapacity
var newCapacity = (long)Capacity; // long to avoid overflow when doubling
do newCapacity *= 2;
while (newCapacity < requiredCapacity);
Resize(newCapacity);
}
#endregion
#region position
private int _position;
/// The remaining we can write into (excluding null-terminator). GetSpan grows first if it's too small.
private Span<TChar> FreeSpan => _storage.AsSpan(_position..^1); // -1 for null terminator
/// Gets the elements written so far. The element immediately after this span is always the null-terminator.
/// Borrowed view: invalidated by any later write or rewind (Append/Clear/Advance/Position). Don't retain it
/// past the next mutation; materialize a copy (WrittenSpan.ToString16()) if you need it to outlive the builder.
public ReadOnlySpan<TChar> WrittenSpan => _storage.AsSpan(.._position);
/// Current write position. Get to capture a savepoint; set (rewind-only) to restore one.
/// Setter is shrink-only: value must be in [0, current Position]. Extending isn't supported -
/// it would expose uninitialized buffer bytes. Use GetSpan + Advance for allocate-then-fill.
public int Position
{
get => _position;
set
{
if ((uint)value > (uint)_position) // uint cast also checks against negative position
throw new ArgumentOutOfRangeException(
nameof(value),
"Position can only be rewound; use Advance to move forward."
);
MoveTo(value);
}
}
/// BCL <see cref="System.Text.StringBuilder.Length"/>-compat alias for <see cref="Position"/>.
/// New code should prefer Position. Unlike BCL, the setter is shrink-only (no zero-fill, no extension);
/// use GetSpan + Advance for allocate-then-fill.
[EditorBrowsable(EditorBrowsableState.Never)]
public int Length
{
get => _position;
set => Position = value;
}
private void MoveTo(int position)
{
_position = position;
_storage[position] = TChar.Zero; // null terminate
}
/// We failed while trying to write: restore our null terminator in case it got clobbered by a partial write.
private bool Fail()
{
_storage[_position] = TChar.Zero; // null terminate
return false;
}
/// We failed while trying to write: restore to checkpoint.
private bool Fail(int checkpoint)
{
MoveTo(checkpoint);
return false;
}
/// <inheritdoc cref="IBufferWriter{TChar}.Advance"/>
public void Advance(int count)
{
if (count < 0 || count > FreeSpan.Length)
throw new ArgumentOutOfRangeException(nameof(count));
MoveTo(_position + count);
}
/// Clears all written content without releasing the underlying buffer.
public void Clear() => MoveTo(0);
#endregion
private Span<TChar> GetSpan(int sizeHint)
{
ArgumentOutOfRangeException.ThrowIfNegative(sizeHint);
var requested = Math.Max(sizeHint, 1);
if (requested > FreeSpan.Length)
GrowBy(requested);
return FreeSpan;
}
private bool TryGetSpan(int contentSizeHint, int alignment, out Span<TChar> destination)
{
var sizeHint = Math.Max(contentSizeHint, Math.Abs(alignment));
destination = FreeSpan;
return destination.Length >= sizeHint;
}
/// Gets or sets the newline sequence used by <see cref="AppendLine{T}"/>. Defaults to <see cref="Environment.NewLine"/>.
public string NewLine = Environment.NewLine;
#region string formatting: IUtf8SpanFormattable, ISpanFormattable, IFormattable
/// <inheritdoc/>
[Obsolete("Allocates. Use WrittenSpan for zero-alloc, or WrittenSpan.ToString16() if you truly want a string.")]
#pragma warning disable CS0809 // Obsolete member overrides non-obsolete member
public override string ToString()
#pragma warning restore CS0809 // Obsolete member overrides non-obsolete member
{
return WrittenSpan.ToString16();
}
/// <inheritdoc/>
/// <remarks><paramref name="format"/> and <paramref name="formatProvider"/> are ignored.</remarks>
string IFormattable.ToString(string? format, IFormatProvider? formatProvider)
{
return WrittenSpan.ToString16();
}
/// <inheritdoc/>
/// <remarks><paramref name="format"/> and <paramref name="provider"/> are ignored.</remarks>
bool ISpanFormattable.TryFormat(
Span<Char16> destination,
out int charsWritten,
ReadOnlySpan<Char16> format,
IFormatProvider? provider
)
{
return Utf<Char16>.TryGetElements(WrittenSpan, destination, out charsWritten);
}
/// <inheritdoc/>
/// <remarks><paramref name="format"/> and <paramref name="provider"/> are ignored.</remarks>
bool IUtf8SpanFormattable.TryFormat(
Span<Char8> destination,
out int bytesWritten,
ReadOnlySpan<Char16> format,
IFormatProvider? provider
)
{
return Utf<Char8>.TryGetElements(WrittenSpan, destination, out bytesWritten);
}
#endregion
}

View file

@ -0,0 +1,44 @@
using System.Numerics;
using Microsoft.Extensions.ObjectPool;
namespace Brutal.Strings;
/// <summary>
/// A pool of <see cref="StringBuilder{TChar}"/> instances for efficient reuse.
/// Thread-safe.
/// StringBuilders with bloated capacity are dropped on return to conserve memory.
/// </summary>
/// <typeparam name="TChar">byte (UTF-8) or char (UTF-16)</typeparam>
public class StringBuilderPool<TChar> : DefaultObjectPool<StringBuilder<TChar>>
where TChar : unmanaged, IBinaryInteger<TChar>
{
private static readonly StringBuilderPolicy Policy = new();
private sealed class StringBuilderPolicy : IPooledObjectPolicy<StringBuilder<TChar>>
{
public StringBuilder<TChar> Create() => new();
public bool Return(StringBuilder<TChar> sb)
{
if (ByteSize.Of<TChar>(sb.Capacity) > ByteSize.FromKilobytes(4))
return false; // drop bloated instances
sb.ResetToDefault();
return true;
}
}
public static readonly StringBuilderPool<TChar> Shared = new();
public StringBuilderPool()
: base(Policy) { }
public StringBuilderPool(int maximumRetained)
: base(Policy, maximumRetained) { }
public StringBuilderPool(IPooledObjectPolicy<StringBuilder<TChar>> policy)
: base(policy) { }
public StringBuilderPool(IPooledObjectPolicy<StringBuilder<TChar>> policy, int maximumRetained)
: base(policy, maximumRetained) { }
}

View file

@ -0,0 +1,53 @@
using System.Diagnostics.Contracts;
using System.Numerics;
namespace Brutal.Strings;
internal static class StringBuilderUtility
{
/// Array.MaxLength - 1 (for null terminator) - copied here because Array.MaxLength isn't const.
/// For reference: Array.MaxLength == int.MaxValue - 56.
public const int ArrayMaxUsableLength = 0X7FFFFFC7 - 1;
extension<TChar>(Span<TChar> value)
where TChar : unmanaged, IBinaryInteger<TChar>
{
[Pure]
public Span<Char8> AsChar8()
{
Debug.Assert(typeof(TChar) == typeof(Char8));
return Unsafe.BitCast<Span<TChar>, Span<Char8>>(value);
}
[Pure]
public Span<Char16> AsChar16()
{
Debug.Assert(typeof(TChar) == typeof(Char16));
return Unsafe.BitCast<Span<TChar>, Span<Char16>>(value);
}
}
extension<TChar>(ReadOnlySpan<TChar> value)
where TChar : unmanaged, IBinaryInteger<TChar>
{
[Pure]
public ReadOnlySpan<Char8> AsChar8()
{
Debug.Assert(typeof(TChar) == typeof(Char8));
return Unsafe.BitCast<ReadOnlySpan<TChar>, ReadOnlySpan<Char8>>(value);
}
[Pure]
public ReadOnlySpan<Char16> AsChar16()
{
Debug.Assert(typeof(TChar) == typeof(Char16));
return Unsafe.BitCast<ReadOnlySpan<TChar>, ReadOnlySpan<Char16>>(value);
}
[Pure]
public String16 ToString16()
{
return typeof(TChar) == typeof(Char8) ? Utf8.GetString(value.AsChar8()) : value.AsChar16().ToString();
}
}
}

View file

@ -0,0 +1,198 @@
// <auto-generated/>
// Stamped from StringBuilder.Append.cs - do not edit; edit the source and rebuild.
#nullable enable
//#define IMPLEMENT_STRING_BUILDER
using System.Buffers;
namespace Brutal.Strings;
#if IMPLEMENT_STRING_BUILDER
public partial class StringBuilder<TChar>
#else
public partial struct ValueStringBuilder<TChar>
#endif
{
private Span<TChar> GetSpan(int contentSizeHint, int alignment)
{
return GetSpan(Math.Max(contentSizeHint, Math.Abs(alignment)));
}
private void Align(Span<TChar> destination, ref int elementsWritten, int alignment)
{
if (alignment == 0)
return;
// Alignment is based on grapheme count, which means we may write more than "alignment",
// i.e. more than we pre-grew for - retry until it fits.
while (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
destination = GetSpan(destination.Length + 1);
}
/// Pads content already written and advanced since <paramref name="start"/> to <paramref name="alignment"/>,
/// growing as needed. Used by nested interpolation: the inner handler writes through directly, then the outer
/// hole's alignment is applied after the fact. <paramref name="start"/> is the position before the inner wrote.
public void AlignFrom(int start, int alignment)
{
if (alignment == 0)
return;
// rewind - don't use MoveTo() as it would null-terminate over its first element
var elementsWritten = _position - start;
_position = start;
Align(FreeSpan, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <summary>Format <paramref name="value"/> into <typeparamref name="TChar"/> elements and append it; the writer grows as needed.</summary>
/// <param name="value">Value to format and append.</param>
/// <param name="alignment">If non-zero, pads the appended content to this many elements (positive: right-align, negative: left-align).</param>
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
/// <param name="provider">Optional format provider.</param>
/// <exception cref="ArgumentOutOfRangeException">The writer's <see cref="IBufferWriter{T}.GetSpan"/> couldn't satisfy the request (e.g. fixed-capacity writer hit its limit).</exception>
public void Append<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
var sizeHint = Math.Abs(alignment);
Span<TChar> destination;
int elementsWritten;
while (!Utf<TChar>.TryFormat(value, destination = GetSpan(sizeHint), out elementsWritten, format, provider))
{
// Format didn't fit - ask for strictly more than what we just got (progress guarantee).
sizeHint = destination.Length + 1;
}
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <summary>Tries to format <paramref name="value"/> into <typeparamref name="TChar"/> elements and append it.</summary>
/// <param name="value">The value to format and append.</param>
/// <param name="alignment">If non-zero, pads the appended content to this many elements (positive: right-align, negative: left-align).</param>
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
/// <param name="provider">Optional format provider.</param>
/// <returns>true on success; false if remaining capacity was insufficient.</returns>
public bool TryAppend<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
if (!TryGetSpan(0, alignment, out var destination))
return false;
if (!Utf<TChar>.TryFormat(value, destination, out var elementsWritten, format, provider))
return Fail(); // can't fit formatted value
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
#region string/ref struct specializations
/// <inheritdoc cref="Append{T}(T, int, string?, IFormatProvider?)" />
public void Append(String8View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
var destination = GetSpan(elementsWritten, alignment); // grow if needed / throw if doesn't fit
Utf<TChar>.GetElements(value, destination);
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <inheritdoc cref="Append{T}(T, int, string?, IFormatProvider?)" />
public void Append(String16View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
var destination = GetSpan(elementsWritten, alignment); // grow if needed / throw if doesn't fit
Utf<TChar>.GetElements(value, destination);
Align(destination, ref elementsWritten, alignment);
Advance(elementsWritten);
}
/// <inheritdoc cref="TryAppend{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppend(String8View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
if (!TryGetSpan(elementsWritten, alignment, out var destination))
return false;
Utf<TChar>.GetElements(value, destination);
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
/// <inheritdoc cref="TryAppend{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppend(String16View value, int alignment = 0)
{
var elementsWritten = Utf<TChar>.GetElementCount(value);
if (!TryGetSpan(elementsWritten, alignment, out var destination))
return false;
Utf<TChar>.GetElements(value, destination);
if (!Utf<TChar>.TryAlign(destination, ref elementsWritten, alignment))
return Fail(); // alignment overflow (grapheme→element shift exceeded pre-grow)
Advance(elementsWritten);
return true;
}
#endregion
#region AppendLine
/// <summary>Append a <see cref="NewLine"/>, growing as needed.</summary>
/// <exception cref="ArgumentOutOfRangeException">The required capacity exceeds the builder's limit.</exception>
public void AppendLine() => Append(NewLine);
/// <summary>Appends <paramref name="value"/> (optionally padded) followed by <see cref="NewLine"/>, growing as needed.</summary>
/// <inheritdoc cref="AppendLine()" path="/exception"/>
public void AppendLine<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
Append(value, alignment, format, provider);
AppendLine();
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public void AppendLine(String8View value, int alignment = 0)
{
Append(value, alignment);
AppendLine();
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public void AppendLine(String16View value, int alignment = 0)
{
Append(value, alignment);
AppendLine();
}
/// Tries to append a <see cref="NewLine"/>.
public bool TryAppendLine() => TryAppend((String16View)NewLine);
/// Tries to append <paramref name="value"/> (optionally padded) followed by <see cref="NewLine"/>.
/// Rolls back atomically on failure.
public bool TryAppendLine<T>(T value, int alignment = 0, string? format = null, IFormatProvider? provider = null)
{
var checkpoint = _position;
if (TryAppend(value, alignment, format, provider) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppendLine(String8View value, int alignment = 0)
{
var checkpoint = _position;
if (TryAppend(value, alignment) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
/// <inheritdoc cref="AppendLine{T}(T, int, string?, IFormatProvider?)" />
public bool TryAppendLine(String16View value, int alignment = 0)
{
var checkpoint = _position;
if (TryAppend(value, alignment) && TryAppendLine())
return true;
return Fail(checkpoint); // restore, in case value was appended but newline wasn't
}
#endregion
}

View file

@ -0,0 +1,87 @@
namespace Brutal.Strings;
public partial struct ValueStringBuilder<TChar>
{
/// Appends an interpolated string.
public void Append([InterpolatedStringHandlerArgument("")] ref Interpolator handler)
{
// Interpolated content appended in a copy, just catch-up with position
_position = handler.Position;
}
/// Appends an interpolated string followed by <see cref="NewLine"/>.
public void AppendLine([InterpolatedStringHandlerArgument("")] ref Interpolator handler)
{
// Interpolated content appended in a copy, just catch-up with position
_position = handler.Position;
AppendLine();
}
/// <summary>
/// Interpolated-string handler for <see cref="ValueStringBuilder{TChar}"/>.
/// Not intended for direct use.
/// </summary>
/// <inheritdoc cref="StringBuilder{TChar}.Interpolator" path="/remarks"/>
[InterpolatedStringHandler, EditorBrowsable(EditorBrowsableState.Never)]
public ref struct Interpolator
{
/*
* A handler can't hold a ref-struct builder by ref (CS9050) or a ref into it (eg ref sb._position),
* so it holds a by-value COPY and Append(ref handler) copies the cursor back.
* The copy shares the same buffer (Span-by-value = same memory),
* so only the cursor diverges - copying back _position suffices.
* A growable builder would copy back the full state (buffer ref + cursor),
* since a grow re-points the span; VSB is fixed, so it doesn't arise.
*/
/// Caution, this is a copy!
private ValueStringBuilder<TChar> _sb;
public int Position => _sb.Length;
public Interpolator(int literalLength, int formattedCount, ValueStringBuilder<TChar> sb)
{
_sb = sb;
}
public void AppendLiteral(String16 value) => _sb.Append((String16View)value);
public void AppendFormatted<T>(T value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment, format);
// ref-struct holes can't flow through AppendFormatted<T> (no `allows ref struct`).
public void AppendFormatted(String8View value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment);
public void AppendFormatted(String16View value, int alignment = 0, String16? format = null) =>
_sb.Append(value, alignment);
public void AppendFormatted(String16? value, int alignment = 0, String16? format = null) =>
_sb.Append((String16View)value, alignment);
#region nested interpolation
/// Builder position captured at construction; only used for nested interpolation alignment.
private readonly int _start;
/// Nested interpolation ctor for <see cref="AppendFormatted(Interpolator, int, String16?)"/>
public Interpolator(int literalLength, int formattedCount, Interpolator parent)
: this(literalLength, formattedCount, parent._sb)
{
_start = parent._sb.Length;
}
// Nested interpolation overload
public void AppendFormatted(
[InterpolatedStringHandlerArgument("")] scoped Interpolator nested,
int alignment = 0,
String16? format = null
)
{
// Interpolated content appended in a copy, just catch-up with position, and align
// NOTE: if VSB ever supports growing, we'd need to copy-back the span as well.
_sb._position = nested.Position;
_sb.AlignFrom(nested._start, alignment);
}
#endregion
}
}

View file

@ -0,0 +1,135 @@
using System.Buffers;
using System.Numerics;
using CommunityToolkit.HighPerformance.Buffers;
namespace Brutal.Strings;
/// <summary>Stack-friendly string builder over a borrowed <see cref="Span{T}"/> buffer. No growth, no allocation.</summary>
/// <inheritdoc cref="StringBuilder{TChar}" path="/remarks"/>
/// <example>
/// <code>
/// var sb = stackalloc byte[256].ToStringBuilder();
/// sb.Append("x="u8);
/// sb.Append(42);
/// // sb.WrittenSpan == "x=42"u8
/// </code>
/// </example>
public ref partial struct ValueStringBuilder<TChar>
where TChar : unmanaged, IBinaryInteger<TChar>
{
/// <param name="buffer">Buffer to write into. Must hold at least 1 element (for the null terminator).</param>
/// <exception cref="ArgumentException"><paramref name="buffer"/> is empty.</exception>
public ValueStringBuilder(Span<TChar> buffer)
{
if (buffer.Length < 1)
throw new ArgumentException(
"Buffer must hold at least 1 element (for the null terminator).",
nameof(buffer)
);
_storage = buffer;
_storage[0] = TChar.Zero;
}
#region storage
private readonly Span<TChar> _storage;
/// Gets the current capacity.
public int Capacity => _storage.Length - 1;
#endregion
#region position
private int _position;
/// The remaining we can write into (excluding null-terminator). GetSpan grows first if it's too small.
private Span<TChar> FreeSpan => _storage[_position..^1]; // -1 for null terminator
/// <inheritdoc cref="StringBuilder{TChar}.WrittenSpan"/>
public ReadOnlySpan<TChar> WrittenSpan => _storage[.._position];
/// <inheritdoc cref="StringBuilder{TChar}.Position"/>
public int Position
{
get => _position;
set
{
if ((uint)value > (uint)_position) // uint cast also checks against negative position
throw new ArgumentOutOfRangeException(
nameof(value),
"Position can only be rewound; use Advance to move forward."
);
MoveTo(value);
}
}
/// <inheritdoc cref="StringBuilder{TChar}.Length"/>
[EditorBrowsable(EditorBrowsableState.Never)]
public int Length
{
get => _position;
set => Position = value;
}
private void MoveTo(int position)
{
_position = position;
_storage[position] = TChar.Zero; // null terminate
}
/// We failed while trying to write: restore our null terminator in case it got clobbered by a partial write.
private bool Fail()
{
_storage[_position] = TChar.Zero; // null terminate
return false;
}
/// We failed while trying to write: restore to checkpoint.
private bool Fail(int checkpoint)
{
MoveTo(checkpoint);
return false;
}
/// <inheritdoc cref="IBufferWriter{TChar}.Advance"/>
public void Advance(int count)
{
if (count < 0 || count > FreeSpan.Length)
throw new ArgumentOutOfRangeException(nameof(count));
MoveTo(_position + count);
}
/// Clears all written content without releasing the underlying buffer.
public void Clear() => MoveTo(0);
#endregion
private Span<TChar> GetSpan(int sizeHint)
{
ArgumentOutOfRangeException.ThrowIfNegative(sizeHint);
var requested = Math.Max(sizeHint, 1);
if (requested > FreeSpan.Length)
throw new ArgumentOutOfRangeException(nameof(Capacity), "Cannot grow.");
return FreeSpan;
}
private bool TryGetSpan(int contentSizeHint, int alignment, out Span<TChar> destination)
{
var sizeHint = Math.Max(contentSizeHint, Math.Abs(alignment));
destination = FreeSpan;
return destination.Length >= sizeHint;
}
/// Gets or sets the newline sequence used by <see cref="AppendLine{T}"/>. Defaults to <see cref="Environment.NewLine"/>.
public string NewLine = Environment.NewLine;
}
public static class CharSpanExtensions
{
/// <inheritdoc cref="ValueStringBuilder{TChar}" />
public static ValueStringBuilder8 ToStringBuilder(this Span<Char8> value) => new(value);
/// <inheritdoc cref="ValueStringBuilder{TChar}" />
public static ValueStringBuilder16 ToStringBuilder(this Span<Char16> value) => new(value);
}