SOURCE DUMP v1

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

View file

@ -0,0 +1,120 @@
using Brutal.Strings;
[assembly: DebuggerTypeProxy(typeof(ByteSpanDebugView), Target = typeof(ReadOnlySpan<byte>))]
[assembly: DebuggerDisplay(
"{Brutal.Strings.ByteSpanDebugView.DebuggerDisplay(this)}",
Target = typeof(ReadOnlySpan<byte>)
)]
[assembly: DebuggerTypeProxy(typeof(ByteSpanDebugView), Target = typeof(Span<byte>))]
[assembly: DebuggerDisplay("{Brutal.Strings.ByteSpanDebugView.DebuggerDisplay(this)}", Target = typeof(Span<byte>))]
[assembly: DebuggerTypeProxy(typeof(ByteSpanDebugView), Target = typeof(Ptr<byte>))]
[assembly: DebuggerDisplay("{Brutal.Strings.ByteSpanDebugView.DebuggerDisplay(this)}", Target = typeof(Ptr<byte>))]
namespace Brutal.Strings;
/// <summary>
/// Allows viewing byte spans as UTF8 strings in the IDE.
/// Does some guesswork (not-100% accurate) to figure out if a span looks like a string vs binary data.
///
/// Supports <see cref="ReadOnlySpan{T}">ReadOnlySpan&lt;byte&gt;</see>, <see cref="Span{T}">Span&lt;byte&gt;</see>, <see cref="Ptr{T}">Ptr&lt;byte&gt;</see>.
/// The containing assembly has to be loaded for the debug view to work.
///
/// Source: https://github.com/dotnet/dotnet/blob/main/src/runtime/src/libraries/System.Private.CoreLib/src/System/SpanDebugView.cs
/// </summary>
internal sealed class ByteSpanDebugView
{
public record struct KindContainer(Kind Kind);
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly KindContainer AKind; // hack so that Kind appears first in the view (debugger sorts on field name, using ASCII sort: 'A', then '_', then 'a')
public readonly string AsUtf8String;
[DebuggerBrowsable(DebuggerBrowsableState.RootHidden)]
public readonly byte[] Items;
public ByteSpanDebugView(ReadOnlySpan<byte> value)
{
(var kind, AsUtf8String) = GetInfo(value);
AKind = new KindContainer(kind);
Items = value.ToArray();
}
public ByteSpanDebugView(Span<byte> span)
: this((ReadOnlySpan<byte>)span) { }
public ByteSpanDebugView(Ptr<byte> ptr)
: this(Utf8.GetNullTerminatedSpan(ptr)) { }
public enum Kind
{
NotEvaluated,
Binary,
BinaryMaybe,
Ascii,
Ansi,
Unicode,
}
static Kind GuessKind(ReadOnlySpan<char> span)
{
var maxChar = 0;
foreach (var c in span)
{
if (char.IsControl(c)) // non-displayable character
return Kind.BinaryMaybe;
maxChar = Math.Max(maxChar, c);
}
return maxChar < 256
? maxChar < 128
? Kind.Ascii
: Kind.Ansi
: Kind.Unicode;
}
static (Kind kind, string value) GetInfo(ReadOnlySpan<byte> value)
{
const int maxLength = 128;
if (value.Length > maxLength)
return (
Kind.NotEvaluated,
$"<Too big, string evaluation disabled (length {value.Length}, max {maxLength})>"
);
if (!Utf8.IsValid(value))
return (Kind.Binary, "<Binary>");
var str = Utf8.GetString(value);
var kind = GuessKind(str);
return (kind, str);
}
static string DebuggerDisplayInternal(ReadOnlySpan<byte> value)
{
var (kind, str) = GetInfo(value);
return kind == Kind.BinaryMaybe ? $"<Binary?> {str}" : str;
}
static string DebuggerDisplay<T>(ReadOnlySpan<T> value)
//where T : unmanaged // don't add constraints, they break the [assembly: DebuggerDisplay] association...
{
Debug.Assert(
typeof(T) == typeof(byte),
"[DebuggerDisplay] requires a generic signature, but we expect only T=byte"
);
var bytes = Unsafe.As<ReadOnlySpan<T>, ReadOnlySpan<byte>>(ref value);
return DebuggerDisplayInternal(bytes);
}
public static string DebuggerDisplay<T>(Ptr<T> value)
where T : unmanaged
{
Debug.Assert(
typeof(T) == typeof(byte),
"[DebuggerDisplay] requires a generic signature, but we expect only T=byte"
);
var span = Utf8.GetNullTerminatedSpan(value.Cast<byte>());
return DebuggerDisplay(span);
}
}

View file

@ -0,0 +1,20 @@
global using System.ComponentModel;
global using System.Diagnostics;
global using System.Runtime.CompilerServices;
global using System.Runtime.InteropServices;
global using Brutal.Memory;
global using Brutal.Pointers;
global using Brutal.Pointers.Extensions;
global using Brutal.Strings.Extensions;
global using CommunityToolkit.HighPerformance;
global using Char16 = char;
global using Char8 = byte;
global using String16 = string;
global using String16View = System.ReadOnlySpan<char>;
global using String8View = System.ReadOnlySpan<byte>;
global using StringBuilder16 = Brutal.Strings.StringBuilder<char>;
global using StringBuilder8 = Brutal.Strings.StringBuilder<byte>;
global using ValueStringBuilder16 = Brutal.Strings.ValueStringBuilder<char>;
global using ValueStringBuilder8 = Brutal.Strings.ValueStringBuilder<byte>;
[assembly: InternalsVisibleTo("Brutal.Strings.Tests")]

View file

@ -0,0 +1,13 @@
namespace Brutal.Strings;
public interface IString<TChar>
where TChar : unmanaged
{
public ReadOnlySpan<TChar> Chars { get; }
public int Length { get; }
public bool IsEmpty { get; }
public TChar this[int index] { get; }
public ReadOnlySpan<TChar> AsSpan();
}

View file

@ -0,0 +1,15 @@
namespace Brutal.Strings;
public interface IString8 : IString<Char8>
{
public String16 ToString16();
}
public static class IString8Extensions
{
public static void CopyTo<T>(this T source, Span<Char8> destination)
where T : IString8, allows ref struct
{
source.Chars.CopyTo(destination);
}
}

View file

@ -0,0 +1,132 @@
using CommunityToolkit.HighPerformance.Buffers;
namespace Brutal.Strings;
public ref struct RefString8Array(ElementCount length, ByteSize numBytes) : IDisposable
{
private readonly SpanOwner<Char8> _owner = SpanOwner<Char8>.Allocate(
(int)(numBytes + ByteSize.Of<int>(length) + ByteSize.Of<nint>(length))
);
public ElementCount Count;
public ElementCount Length = length;
public ByteSize NumBytes = numBytes;
private bool _disposed = false;
public RefString8Array(ReadOnlySpan<String16> strings)
: this(strings.Length, GetTotalByteCount(strings))
{
var written = 0;
var bytes = _owner.Span;
var offsets = bytes[(int)NumBytes..].Cast<Char8, int>();
for (var i = 0; i < strings.Length; i++)
{
// Assert null terminator
Debug.Assert(written == 0 || bytes[written - 1] == 0);
offsets[i] = written;
written += Utf8.GetBytes(strings[i], bytes[written..]);
bytes[written++] = 0;
}
Debug.Assert(written == (int)NumBytes);
}
public RefString8Array(ReadOnlySpan<String8> strings)
: this(strings.Length, GetTotalByteCount(strings))
{
var written = 0;
var bytes = _owner.Span;
var offsets = bytes[(int)NumBytes..].Cast<Char8, int>();
for (var i = 0; i < strings.Length; i++)
{
// Assert null terminator
Debug.Assert(written == 0 || bytes[written - 1] == 0);
offsets[i] = written;
strings[i].CopyTo(bytes[written..]);
written += strings[i].Length;
bytes[written++] = 0;
}
Debug.Assert(written == (int)NumBytes);
}
public unsafe Char8** CommitFixedRegion(Char8* fixedPointer)
{
if (_disposed)
throw new ObjectDisposedException(nameof(RefString8Array));
Debug.Assert(fixedPointer == Unsafe.AsPointer(ref _owner.Span[0]));
var bytes = new Span<Char8>(fixedPointer, _owner.Span.Length);
var offsets = bytes[(int)NumBytes..].Cast<Char8, int>();
var pointers = offsets[(int)Length..].Cast<int, nint>();
for (var i = 0; i < Length; i++)
{
pointers[i] = (nint)fixedPointer + offsets[i];
}
return (Char8**)pointers.AsPointer();
}
public void AppendString(ReadOnlySpan<Char8> str)
{
if (_disposed)
throw new ObjectDisposedException(nameof(RefString8Array));
if (Count == Length)
throw new InvalidOperationException("Array is full");
_owner.Span[(int)(NumBytes + ByteSize.Of<nint>(Count))] = (Char8)str.Length;
str.CopyTo(_owner.Span[(int)(NumBytes + ByteSize.Of<nint>(Count) + 1)..]);
Count++;
}
public static ByteSize GetTotalByteCount(ReadOnlySpan<String8> strings)
{
var count = 0;
foreach (var str in strings)
count += str.Length + 1;
return (ByteSize)count;
}
public static ByteSize GetTotalByteCount(ReadOnlySpan<String16> strings)
{
var count = 0;
foreach (var str in strings)
count += Utf8.GetByteCount(str) + 1;
return (ByteSize)count;
}
public ref Char8 GetPinnableReference()
{
if (_disposed)
throw new ObjectDisposedException(nameof(RefString8Array));
return ref _owner.Span[0];
}
public static implicit operator RefString8Array(ReadOnlySpan<String8> strings) => new(strings);
public static implicit operator RefString8Array(ReadOnlySpan<String16> strings) => new(strings);
public static implicit operator RefString8Array(Span<String8> strings) => new(strings);
public static implicit operator RefString8Array(Span<String16> strings) => new(strings);
public static implicit operator RefString8Array(String8[] strings) => new(strings);
public static implicit operator RefString8Array(String16[] strings) => new(strings);
public void Dispose()
{
if (_disposed)
return;
_disposed = true;
_owner.Dispose();
}
}

View file

@ -0,0 +1,14 @@
namespace Brutal.Strings.Extensions;
public static class SpanExtensions
{
public static String16 ToString16(this Span<Char8> span)
{
return Utf8.GetString(span);
}
public static String16 ToString16(this String8View span)
{
return Utf8.GetString(span);
}
}

View file

@ -0,0 +1,118 @@
using System.Runtime.InteropServices.Marshalling;
using Brutal.Attributes;
namespace Brutal.Strings;
/// <summary>
/// A reference to a null-terminated string of bytes.
/// </summary>
[DebuggerDisplay("{ToString16()}")]
[NativeMarshalling(typeof(RefString8Marshaller))]
public readonly ref struct RefString8 : IString8
{
private readonly ref Char8 _firstChar;
public static RefString8 Empty => String8View.Empty;
/// <summary>
/// Create a safe reference to a null-terminated string of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public RefString8(String8View cString)
{
_firstChar = ref MemoryMarshal.GetReference(cString);
}
/// <summary>
/// Create an unsafe reference to a null-terminated string of bytes.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public unsafe RefString8([Fixed] Ptr<Char8> pointer)
{
_firstChar = ref Unsafe.AsRef<Char8>(pointer);
}
/// <summary>
/// Get a reference to the first character of the string.
/// </summary>
public ref Char8 FirstChar
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
get => ref _firstChar;
}
/// <summary>
/// Implicit conversion from a null-terminated string of bytes to a RefString8.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RefString8([Fixed] Ptr<Char8> cString)
{
return new RefString8(cString);
}
/// <summary>
/// Implicit conversion from a String8View to a RefString8.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RefString8(String8View bytes)
{
return new RefString8(bytes);
}
/// <summary>
/// Implicit conversion from a Span&lt;Char8&gt; to a RefString8.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RefString8(Span<Char8> bytes)
{
return new RefString8(bytes);
}
/// <summary>
/// Implicit conversion from a byte array to a RefString8.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RefString8(Char8[] bytes)
{
return new RefString8(bytes);
}
/// <summary>
/// Implicit conversion from a String8 to a RefString8.
/// </summary>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static implicit operator RefString8(String8 cString)
{
return new RefString8(cString.AsSpan());
}
public static implicit operator String8View(RefString8 str)
{
return str.Chars;
}
/// <summary>
/// Get a reference to the first character of the string.
/// </summary>
public ref Char8 GetPinnableReference()
{
return ref _firstChar;
}
public unsafe String8View Chars => Utf8.GetNullTerminatedSpan((Ptr<Char8>)Unsafe.AsPointer(ref _firstChar));
public int Length => Chars.Length;
public bool IsEmpty => Unsafe.IsNullRef(ref _firstChar) || _firstChar == 0;
public Char8 this[int index] => Chars[index];
public String8View this[Range range] => Chars[range];
public String8View AsSpan()
{
return Chars;
}
public String16 ToString16()
{
return Utf8.GetString(Chars);
}
}

View file

@ -0,0 +1,33 @@
using System.Runtime.InteropServices.Marshalling;
using Brutal.Attributes;
namespace Brutal.Strings;
[CustomMarshaller(
managedType: typeof(RefString8),
marshalMode: MarshalMode.ManagedToUnmanagedIn,
marshallerType: typeof(RefString8Marshaller)
)]
[CustomMarshaller(
managedType: typeof(RefString8),
marshalMode: MarshalMode.UnmanagedToManagedIn,
marshallerType: typeof(RefString8Marshaller)
)]
public static class RefString8Marshaller
{
public static unsafe Char8* ConvertToUnmanaged(RefString8 managed)
{
return (Char8*)Unsafe.AsPointer(ref managed.GetPinnableReference());
}
// pointer is [Fixed] because it originates from native interop / owned by the unmanaged side
public static unsafe RefString8 ConvertToManaged([Fixed] Char8* unmanaged)
{
return new RefString8(unmanaged);
}
public static ref Char8 GetPinnableReference(RefString8 managed)
{
return ref managed.GetPinnableReference();
}
}

View file

@ -0,0 +1,204 @@
namespace Brutal.Strings;
/// <summary>
/// Represents a string backed by an array of bytes.
/// </summary>
/// <remarks>
/// Typically, but not necessarily, the bytes are UTF-8 encoded. Note that this type doesn't provide any special UTF-8 functionality.
/// </remarks>
[DebuggerDisplay("{ToString16()}")]
public class String8 : IString8, IEquatable<String8?>, IComparable, IComparable<String8?>, ICloneable
{
/// the default array backing any empty-initialized String8
private static readonly Char8[] EmptyChars = [0];
/// <summary>
/// An empty string8.
/// </summary>
public static readonly String8 Empty = new();
/// WARNING: This array contains a trailing null byte.
private readonly Char8[] _bytes;
public String8View Chars => _bytes.AsSpan()[..^1];
/// <summary>
/// Construct an empty string.
/// </summary>
public String8()
{
_bytes = EmptyChars;
}
/// <summary>
/// Construct a string from a list of characters (converting to UTF-8 in the process).
/// </summary>
public String8(String16View characters)
{
if (characters.IsEmpty)
{
_bytes = EmptyChars;
}
else
{
_bytes = new Char8[Utf8.GetByteCount(characters) + 1];
Utf8.GetBytes(characters, _bytes);
}
}
/// <summary>
/// Construct a string from a list of bytes (no conversion, but copies).
/// </summary>
/// <param name="bytes"></param>
public String8(String8View bytes)
{
if (bytes.IsEmpty)
{
_bytes = EmptyChars;
}
else
{
_bytes = new Char8[bytes.Length + 1];
bytes.CopyTo(_bytes);
}
}
/// <summary>
/// Construct a string from an existing array of bytes.
/// </summary>
/// <remarks>
/// Private because this behavior is dangerous if the array can be modified after construction.
/// </remarks>
private String8(Char8[] bytes)
{
if (bytes[^1] != 0)
throw new ArgumentException("'bytes' must be null-terminated!", nameof(bytes));
_bytes = bytes.Length != 0 ? bytes : EmptyChars;
}
/// <summary>
/// The length of the string in bytes.
/// </summary>
public int Length => _bytes.Length - 1;
public bool IsEmpty => Length == 0;
/// <summary>
/// Create a new String8 from a slice of the current string.
/// </summary>
public String8 Slice(int startIndex)
{
return new String8(Chars[startIndex..]);
}
/// <summary>
/// Create a new String8 from a slice of the current string.
/// </summary>
public String8 Slice(int startIndex, int count)
{
return new String8(Chars[startIndex..(startIndex + count)]);
}
public Char8 this[int index] => Chars[index];
public String8 this[Range range] => new String8(Chars[range]);
public object Clone()
{
// do not call the byte[] constructor here!
return new String8(AsSpan());
}
#region Operators
public static implicit operator String8View(String8 str)
{
return str.Chars;
}
public static implicit operator String8(String8View str)
{
return new String8(str);
}
#endregion
public String8View AsSpan()
{
return Chars;
}
public string ToString16()
{
return Utf8.GetString(Chars);
}
// Equality and comparison implementations
public bool Equals(String8? other)
{
if (ReferenceEquals(this, other))
return true;
if (other is null || Length != other.Length)
return false;
return Chars.SequenceEqual(other.Chars);
}
public override bool Equals(object? obj)
{
return obj is String8 other && Equals(other);
}
public override int GetHashCode()
{
return Chars.GetDjb2HashCode();
}
public int CompareTo(object? obj)
{
if (obj is null)
return 1;
if (obj is not String8 other)
throw new ArgumentException("Object must be of type String8.", nameof(obj));
return CompareTo(other);
}
public int CompareTo(String8? other)
{
if (other is null)
return 1;
return Chars.AsBytes().SequenceCompareTo(other.Chars);
}
public static bool operator ==(String8? a, String8? b)
{
if (ReferenceEquals(a, b))
return true;
if (a is null || b is null)
return false;
return a.Equals(b);
}
public static bool operator !=(String8? a, String8? b)
{
return !(a == b);
}
/// <summary>
/// Create a new string from existing memory without copying.
/// </summary>
/// <remarks>
/// WARNING: Do not retain the provided bytes after constructing the String8. The String8 instance will take ownership of the memory.
/// </remarks>
public static String8 Move(Char8[] bytes)
{
if (bytes.Length != 0 && bytes[^1] != 0)
return new String8(bytes.AsSpan());
return new String8(bytes);
}
public ref Char8 GetPinnableReference()
{
return ref _bytes[0];
}
}

View file

@ -0,0 +1,126 @@
namespace Brutal.Strings;
public static partial class String8Extensions
{
private static class Helpers
{
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static int CompareOrdinalHelper(
String8View strA,
int indexA,
int countA,
String8View strB,
int indexB,
int countB
)
{
Debug.Assert(!strA.IsEmpty);
Debug.Assert(!strB.IsEmpty);
Debug.Assert(indexA >= 0 && indexB >= 0);
Debug.Assert(countA >= 0 && countB >= 0);
Debug.Assert(indexA + countA <= strA.Length && indexB + countB <= strB.Length);
return strA.Slice(indexA, countA).SequenceCompareTo(strB.Slice(indexB, countB));
}
public static int CompareOrdinalHelper(String8View strA, String8View strB)
{
return strA.SequenceCompareTo(strB);
}
}
// Provides an ordinal string comparison. strA is compared to strB
// to determine whether it is lexicographically less, equal, or greater, and then a
// negative integer, 0, or a positive integer is returned; respectively.
public static int Compare<TString8>(this TString8 strA, String8View strB)
where TString8 : IString8, allows ref struct
{
// They can't both be null at this point.
if (strA.IsEmpty)
{
return -1;
}
if (strB.IsEmpty)
{
return 1;
}
return Helpers.CompareOrdinalHelper(strA.Chars, strB);
}
// Compares strA and strB using an ordinal (code-point) comparison.
public static int Compare<TString8>(this TString8 strA, int indexA, String8View strB, int indexB, int length)
where TString8 : IString8, allows ref struct
{
if (strA.IsEmpty || strB.IsEmpty)
{
return strA.IsEmpty ? -1 : 1;
}
ArgumentOutOfRangeException.ThrowIfNegative(length);
if (indexA < 0 || indexB < 0)
{
string paramName = indexA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(paramName, "Index cannot be negative.");
}
int lengthA = Math.Min(length, strA.Length - indexA);
int lengthB = Math.Min(length, strB.Length - indexB);
if (lengthA < 0 || lengthB < 0)
{
string paramName = lengthA < 0 ? nameof(indexA) : nameof(indexB);
throw new ArgumentOutOfRangeException(
paramName,
"Index and length must refer to a location within the string."
);
}
if (length == 0)
{
return 0;
}
return Helpers.CompareOrdinalHelper(strA.Chars, indexA, lengthA, strB, indexB, lengthB);
}
// Determines whether a specified string is a suffix of the current instance.
public static bool EndsWith<TString8>(this TString8 str, String8View value)
where TString8 : IString8, allows ref struct
{
int offset = str.Length - value.Length;
return (uint)offset <= (uint)str.Length && str.Chars[offset..].SequenceEqual(value);
}
public static bool EndsWith<TString8>(this TString8 str, Char8 value)
where TString8 : IString8, allows ref struct
{
int lastPos = str.Length - 1;
return ((uint)lastPos < (uint)str.Length) && str[lastPos].Equals(value);
}
// Determines whether a specified string is a prefix of the current instance
public static bool StartsWith<TString8>(this TString8 str, String8View value)
where TString8 : IString8, allows ref struct
{
if (value.IsEmpty)
{
return true;
}
if (value.Length > str.Length)
{
return false;
}
return str.Chars[..value.Length].SequenceEqual(value);
}
public static bool StartsWith<TString8>(this TString8 str, Char8 value)
where TString8 : IString8, allows ref struct
{
return str.Length != 0 && str[0].Equals(value);
}
}

View file

@ -0,0 +1,146 @@
namespace Brutal.Strings;
public static partial class String8Extensions
{
public static bool Contains<TString8>(this TString8 str, String8View value)
where TString8 : IString8, allows ref struct
{
return str.IndexOf(value) >= 0;
}
public static bool Contains<TString8>(this TString8 str, Char8 value)
where TString8 : IString8, allows ref struct
{
return str.Chars.Contains(value);
}
// Returns the index of the first occurrence of a specified character in the current instance.
// The search starts at startIndex and runs thorough the next count characters.
public static int IndexOf<TString8>(this TString8 str, Char8 value)
where TString8 : IString8, allows ref struct => str.Chars.IndexOf(value);
public static int IndexOf<TString8>(this TString8 str, Char8 value, int startIndex)
where TString8 : IString8, allows ref struct
{
return IndexOf(str, value, startIndex, str.Length - startIndex);
}
public static int IndexOf<TString8>(this TString8 str, Char8 value, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var result = str.Chars.Slice(startIndex, count).IndexOf(value);
return result < 0 ? result : result + startIndex;
}
// Returns the index of the first occurrence of any specified character in the current instance.
// The search starts at startIndex and runs to startIndex + count - 1.
//
public static int IndexOfAny<TString8>(this TString8 str, String8View anyOf)
where TString8 : IString8, allows ref struct
{
return str.Chars.IndexOfAny(anyOf);
}
public static int IndexOfAny<TString8>(this TString8 str, String8View anyOf, int startIndex)
where TString8 : IString8, allows ref struct
{
return IndexOfAny(str, anyOf, startIndex, str.Length - startIndex);
}
public static int IndexOfAny<TString8>(this TString8 str, String8View anyOf, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var result = str.Chars.Slice(startIndex, count).IndexOfAny(anyOf);
return result < 0 ? result : result + startIndex;
}
public static int IndexOf<TString8>(this TString8 str, String8View value)
where TString8 : IString8, allows ref struct
{
return str.Chars.IndexOf(value);
}
public static int IndexOf<TString8>(this TString8 str, String8View value, int startIndex)
where TString8 : IString8, allows ref struct
{
var result = str.Chars[startIndex..].IndexOf(value);
return result < 0 ? result : result + startIndex;
}
public static int IndexOf<TString8>(this TString8 str, String8View value, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var result = str.Chars.Slice(startIndex, count).IndexOf(value);
return result < 0 ? result : result + startIndex;
}
// Returns the index of the last occurrence of a specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
public static int LastIndexOf<TString8>(this TString8 str, Char8 value)
where TString8 : IString8, allows ref struct => str.Chars.LastIndexOf(value);
public static int LastIndexOf<TString8>(this TString8 str, Char8 value, int startIndex)
where TString8 : IString8, allows ref struct
{
return LastIndexOf(str, value, startIndex, startIndex + 1);
}
public static int LastIndexOf<TString8>(this TString8 str, Char8 value, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var result = str.Chars.Slice(startIndex, count).LastIndexOf(value);
return result < 0 ? result : result + startIndex;
}
// Returns the index of the last occurrence of any specified character in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public static int LastIndexOfAny<TString8>(this TString8 str, String8View anyOf)
where TString8 : IString8, allows ref struct
{
return str.Chars.LastIndexOfAny(anyOf);
}
public static int LastIndexOfAny<TString8>(this TString8 str, String8View anyOf, int startIndex)
where TString8 : IString8, allows ref struct
{
return LastIndexOfAny(str, anyOf, startIndex, startIndex + 1);
}
public static int LastIndexOfAny<TString8>(this TString8 str, String8View anyOf, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var actualStartIndex = startIndex - count + 1;
var result = str.Chars.Slice(actualStartIndex, count).LastIndexOfAny(anyOf);
return result < 0 ? result : result + actualStartIndex;
}
// Returns the index of the last occurrence of any character in value in the current instance.
// The search starts at startIndex and runs backwards to startIndex - count + 1.
// The character at position startIndex is included in the search. startIndex is the larger
// index within the string.
//
public static int LastIndexOf<TString8>(this TString8 str, String8View value)
where TString8 : IString8, allows ref struct
{
return LastIndexOf(str, value, str.Length - 1, str.Length);
}
public static int LastIndexOf<TString8>(this TString8 str, String8View value, int startIndex)
where TString8 : IString8, allows ref struct
{
return LastIndexOf(str, value, startIndex, startIndex + 1);
}
public static int LastIndexOf<TString8>(this TString8 str, String8View value, int startIndex, int count)
where TString8 : IString8, allows ref struct
{
var actualStartIndex = startIndex - count + 1;
var result = str.Chars.Slice(actualStartIndex, count).LastIndexOf(value);
return result < 0 ? result : result + actualStartIndex;
}
}

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);
}

View file

@ -0,0 +1,90 @@
using System.Buffers;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Numerics;
using System.Text;
namespace Brutal.Strings;
public static class Unicode
{
// TODO: should all these be extensions?
// TODO: do we also need GetCellWidth()? approximate terminal-cell width of a single rune (wcwidth-style)
/// Count the number of runes (code points) in a string,
/// leniently: each invalid sequence counts as one replacement.
[Pure]
public static int GetRuneCount(String16View value)
{
var count = 0;
var runes = value.EnumerateRunes();
while (runes.MoveNext())
count++;
return count;
}
/// <inheritdoc cref="GetRuneCount(String16View)" />
[Pure]
public static int GetRuneCount(String8View value)
{
var count = 0;
while (true)
{
var status = Rune.DecodeFromUtf8(value, out _, out var bytesConsumed);
if (status == OperationStatus.NeedMoreData)
{
// bytesConsumed == 0 -> end of input (clean)
// bytesConsumed > 0 -> trailing partial: count as one replacement,
// matching the UTF-16 EnumerateRunes() which counts a lone surrogate the same way.
if (bytesConsumed > 0)
count++;
return count;
}
value = value[bytesConsumed..];
count++;
}
}
/// <inheritdoc cref="GetRuneCount(String16View)" />
[Pure]
public static int GetRuneCount<TChar>(ReadOnlySpan<TChar> value)
where TChar : unmanaged, IBinaryInteger<TChar>
{
return typeof(TChar) == typeof(Char8) ? GetRuneCount(value.AsChar8()) : GetRuneCount(value.AsChar16());
}
/// Count the number of graphemes in a string.
[Pure]
public static int GetGraphemeCount(String16View value)
{
var count = 0;
while (!value.IsEmpty)
{
var next = StringInfo.GetNextTextElementLength(value);
if (next == 0)
break; // TODO: null-terminator is somewhat unexpected, should we throw instead?
value = value[next..];
count++;
}
return count;
}
/// <inheritdoc cref="GetGraphemeCount(String16View)" />
[Pure]
public static int GetGraphemeCount(String8View value)
{
using (Utf8.GetChars(value, stackalloc Char16[256], out var chars))
{
return GetGraphemeCount(chars);
}
}
/// <inheritdoc cref="GetGraphemeCount(String16View)" />
[Pure]
public static int GetGraphemeCount<TChar>(ReadOnlySpan<TChar> value)
where TChar : unmanaged, IBinaryInteger<TChar>
{
return typeof(TChar) == typeof(Char8) ? GetGraphemeCount(value.AsChar8()) : GetGraphemeCount(value.AsChar16());
}
}

Some files were not shown because too many files have changed in this diff Show more