SOURCE DUMP v1

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

View file

@ -0,0 +1,122 @@
namespace Brutal.Strings;
using ArenaString = ReadOnlySpan<Char8>;
/// <summary>
/// Packs multiple null-terminated strings (aka chunks) into one fixed-capacity <see cref="StringBuilder{TChar}"/>.
/// The buffer never reallocates (Capacity == MaxCapacity), so every span handed out stays valid
/// until the next <see cref="Clear"/>. Being an arena, the suggested lifetime is a frame / tick.
/// Each chunk owns a trailing <c>\0</c> terminator, so beginning or growing one needs room:
/// throws <see cref="ArgumentOutOfRangeException"/> when the arena is full.
/// </summary>
public class ArenaStringBuilder(int capacity)
{
// Fixed capacity: cannot grow as a realloc would dangle every mid-flight chunk.
private readonly StringBuilder8 _sb = new(capacity: capacity, maxCapacity: capacity);
/// <inheritdoc cref="StringBuilder{TChar}.Clear" />
public void Clear() => _sb.Clear();
/// Begins a chunk (empty span at the current position).
public ArenaString Begin()
{
// StringBuilder keeps a \0 at Contents.Length: skip 1 to avoid clobbering the previous chunk's null-terminator.
if (_sb.WrittenSpan.Length > 0)
_sb.Advance(1);
var contents = _sb.WrittenSpan;
return contents[contents.Length..]; // empty span at the current write position
}
/// Returns the span from <paramref name="origin"/> to the builder's current write position.
public void Extend(scoped ref ArenaString origin)
{
var contents = _sb.WrittenSpan;
var start = (int)
Unsafe.ByteOffset(in MemoryMarshal.GetReference(contents), in MemoryMarshal.GetReference(origin));
origin = contents[start..];
}
/// Appends <paramref name="value"/> to the <paramref name="origin"/> chunk.
public void Append<T>(ref ArenaString origin, T value, int alignment = 0, String16? format = null)
{
_sb.Append(value, alignment, format);
Extend(ref origin);
}
/// <inheritdoc cref="Append{T}"/>
public void Append(ref ArenaString origin, scoped ReadOnlySpan<Char8> value, int alignment = 0)
{
_sb.Append(value, alignment);
Extend(ref origin);
}
/// <inheritdoc cref="Append{T}"/>
public void Append(ref ArenaString origin, scoped ReadOnlySpan<Char16> value, int alignment = 0)
{
_sb.Append(value, alignment);
Extend(ref origin);
}
/// Appends and returns a standalone chunk.
public ArenaString Append(String8View value)
{
var origin = Begin();
_sb.Append(value);
Extend(ref origin);
return origin;
}
/// <inheritdoc cref="Append(String8View)"/>
public ArenaString Append(ReadOnlySpan<Char16> value)
{
var origin = Begin();
_sb.Append(value);
Extend(ref origin);
return origin;
}
/// Folds a hole's <paramref name="value"/> into the <paramref name="origin"/> chunk.
public void Absorb(ref ArenaString origin, scoped ArenaString value, int alignment = 0)
{
/*
* The value may have arrived three ways, told apart by where it sits relative to our chunk:
* - nested $"...": written straight through our chunk (starts exactly where we end) -> absorb in place;
* - inline string/char->ImString conversion: wrote mid-flight, landing at our tail behind its own Begin
* separator -> rewind over the stray bytes and re-lay contiguously;
* - external (u8 literal, a variable's span): not in the arena -> just copy it in.
*/
var written = _sb.WrittenSpan;
ref var baseRef = ref MemoryMarshal.GetReference(written);
var valueOffset = Unsafe.ByteOffset(in baseRef, in MemoryMarshal.GetReference(value));
var originEnd = (int)Unsafe.ByteOffset(in baseRef, in MemoryMarshal.GetReference(origin)) + origin.Length;
// Only trust the offset math if `value` actually lives in our arena buffer (offset within [0, Capacity]).
if ((nuint)valueOffset <= (nuint)_sb.Capacity)
{
var valueStart = (int)valueOffset;
if (valueStart == originEnd) // nested write-through: already part of our chunk
{
if (alignment != 0)
AlignFrom(ref origin, value, alignment);
else
Extend(ref origin);
return;
}
if (valueStart + value.Length == written.Length) // inline conversion that wrote at our tail
_sb.Position = originEnd; // rewind over its stray bytes (Begin separator + content) before re-laying
}
// Re-lay (or copy) the value contiguously at the chunk end. When rewound, this is a forward copy with
// dest (originEnd) < src (valueStart) - memmove-safe even though value aliases the tail.
Append(ref origin, value, alignment);
}
/// <inheritdoc cref="StringBuilder{TChar}.AlignFrom"/>
public void AlignFrom(ref ArenaString origin, scoped ArenaString nested, int alignment)
{
var start = (int)
Unsafe.ByteOffset(in MemoryMarshal.GetReference(_sb.WrittenSpan), in MemoryMarshal.GetReference(nested));
_sb.AlignFrom(start, alignment);
Extend(ref origin);
}
}

View file

@ -0,0 +1,114 @@
namespace Brutal.ImGuiApi;
/// A UTF8 mutable string, for ImGui InputText() etc.
/// Heap-allocated.
public class ImInputString : IUtf8SpanFormattable, ISpanFormattable
{
public readonly byte[] Buffer;
public int Capacity => Buffer.Length;
public int Length;
public ImInputString(int capacity, ReadOnlySpan<byte> initialContent = default)
{
if (capacity < 1)
throw new ArgumentOutOfRangeException(
nameof(capacity),
"Capacity must be at least 1 to accommodate null-terminator."
);
Buffer = new byte[capacity];
SetValue(initialContent);
}
public ImInputString(int capacity, ImString initialContent)
: this(capacity, initialContent.AsSpan()) { }
public void SetValue(ReadOnlySpan<byte> content)
{
Length = Utf8.EvaluateLength(content);
ValidateLength();
if (Length > 0)
content[..Length].CopyTo(Buffer);
NullTerminate();
}
public void SetValue(ReadOnlySpan<char> content)
{
Utf8.FromUtf16(content, Buffer, out _, out Length);
ValidateLength();
NullTerminate();
}
public void Clear()
{
Length = 0;
NullTerminate();
}
/// <inheritdoc cref="Utf8.EvaluateLength(ReadOnlySpan{byte})"/>
public void EvaluateLength()
{
Length = Utf8.EvaluateLength(Buffer);
ValidateLength();
}
private void ValidateLength()
{
if (Length >= Capacity)
throw new Exception("Length must be less than Capacity to accommodate null-terminator.");
}
private void NullTerminate()
{
Buffer[Length] = 0;
}
public bool IsEmpty => Length == 0;
/// for PInvoke
public ref readonly byte GetPinnableReference() => ref MemoryMarshal.GetArrayDataReference(Buffer);
public ReadOnlySpan<byte> ValueSpan => Buffer.AsSpan()[..Length];
//public static implicit operator ReadOnlySpan<byte>(ImInputString input) => input.ValueSpan;
public ImString Value => ValueSpan;
public ReadOnlySpan<byte> Value8
{
set => SetValue(value);
}
public ReadOnlySpan<char> Value16
{
set => SetValue(value);
}
public static implicit operator ImString(ImInputString input) => input.ValueSpan;
#region IUtf8SpanFormattable, ISpanFormattable, IFormattable
/// IUtf8SpanFormattable implementation
public bool TryFormat(
Span<byte> utf8Destination,
out int bytesWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider
) => Value.TryFormat(utf8Destination, out bytesWritten, format, provider);
/// ISpanFormattable implementation
public bool TryFormat(
Span<char> utf16Destination,
out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider
) => Value.TryFormat(utf16Destination, out charsWritten, format, provider);
/// IFormattable implementation - useless but required for ISpanFormattable
string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => Value.ToString();
public override string ToString() => Value.ToString();
#endregion
}
public static class ImInputStringExtensions
{
public static bool IsNullOrEmpty(this ImInputString? @this) => @this == null || @this.Length == 0;
}

View file

@ -0,0 +1,94 @@
using System.ComponentModel;
namespace Brutal.ImGuiApi;
[InterpolatedStringHandler]
public ref partial struct ImString
{
/*
* Interpolation handler for ImString. Each piece is appended to the shared arena builder,
* which centralizes formatting, grapheme-aware alignment, and nested-interpolation write-through;
* then `_bytes` is extended to span the chunk built so far.
* The arena maintains a null terminator just past each chunk for native interop.
*/
/// InterpolatedStringHandler constructor; not intended for general use.
[EditorBrowsable(EditorBrowsableState.Never)]
public ImString(int literalLength, int formattedCount)
{
if (literalLength + formattedCount == 0)
{
// special case for empty interpolation: $""
this = Empty;
return;
}
_bytes = SharedStorage.Begin(); // empty span anchored at the chunk start; grown by each Append below
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendLiteral(scoped ReadOnlySpan<char> value)
{
SharedStorage.Append(ref _bytes, value);
}
#region AppendFormatted() for string types (UTF16 and UTF8)
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendFormatted(String8 value, int alignment = 0, string? format = null) // no custom format, but we still declare the overload for compatibility
{
SharedStorage.Append(ref _bytes, value.AsSpan(), alignment);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendFormatted(String16 value, int alignment = 0, string? format = null) // no custom format, but we still declare the overload for compatibility
{
SharedStorage.Append(ref _bytes, value.AsSpan(), alignment);
}
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendFormatted(scoped ReadOnlySpan<char> value, int alignment = 0, string? format = null) // no custom format, but we still declare the overload for compatibility
{
SharedStorage.Append(ref _bytes, value, alignment);
}
/// This assumes that value is a UTF8 string, rather than actual binary bytes...
/// TODO: we could use a format string to disambiguate? Also see Utf8.IsValid(value)
[EditorBrowsable(EditorBrowsableState.Never)]
[OverloadResolutionPriority(1)] // disambiguates holes convertible to both ROS<byte> and ImString; both fold via Absorb
public void AppendFormatted(scoped ReadOnlySpan<byte> value, int alignment = 0, string? format = null) // no custom format, but we still declare the overload for compatibility
{
SharedStorage.Absorb(ref _bytes, value, alignment);
}
#endregion
/// Kitchen-sink formatting through <see cref="Utf8.TryFormat{T}"/> / <see cref="StringBuilder{TChar}.Append{T}"/>.
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendFormatted<T>(T value, int alignment = 0, string? format = null)
{
SharedStorage.Append(ref _bytes, value, alignment, format);
}
#region nested interpolation
/// Nested interpolation ctor for <see cref="AppendFormatted(ImString, int, String16?)"/>
[EditorBrowsable(EditorBrowsableState.Never)]
public ImString(int literalLength, int formattedCount, ImString parent)
{
_bytes = parent._bytes[^0..]; // continue the parent's chunk
}
/// Folds an ImString hole - a nested $"..." written through our chunk, or any other value - into this chunk.
[EditorBrowsable(EditorBrowsableState.Never)]
public void AppendFormatted(
[InterpolatedStringHandlerArgument("")] scoped ImString value,
int alignment = 0,
string? format = null
)
{
SharedStorage.Absorb(ref _bytes, value._bytes, alignment);
}
#endregion
}

View file

@ -0,0 +1,42 @@
namespace Brutal.ImGuiApi;
public ref partial struct ImString
{
/*
* This partial provides helpers to interface with APIs that take regular C# strings.
* Ideally should be removed in a stricter implementation, to avoid accidental conversions.
* Also, the StringPool dictionary is naive, leaks etc.
*/
// TODO: I would like to make the string conversion operator explicit,
// unfortunately it is necessary to support ImString inside DefaultInterpolatedStringHandler...
public static implicit operator string(in ImString s) => s.ToString();
private class StringPool
{
private readonly Dictionary<int, string> _utf8ToString = new();
public string ToString(ReadOnlySpan<byte> bytes)
{
var hash = new HashCode();
hash.AddBytes(bytes);
var key = hash.ToHashCode();
if (!_utf8ToString.TryGetValue(key, out var toString))
{
toString = Utf8.GetString(bytes);
_utf8ToString.Add(key, toString);
}
return toString;
}
}
private static readonly StringPool SharedStringPool = new();
public static bool CacheToString = true;
public override string ToString()
{
if (!CacheToString)
return Utf8.GetString(_bytes);
return SharedStringPool.ToString(_bytes);
}
}

View file

@ -0,0 +1,126 @@
using System.Buffers;
using Brutal.Localization;
namespace Brutal.ImGuiApi;
/// A UTF8 ref-string, for passing to ImGui API.
/// Allocated in an arena buffer -> life-span of one frame (or less), cannot be retained.
public ref partial struct ImString : IUtf8SpanFormattable, ISpanFormattable, INullable
{
public class Storage(int capacity) : ArenaStringBuilder(capacity)
{
// TODO: mark [Obsolete] / replace with ImString.Clear()
public void Reset() => Clear();
}
public static readonly Storage SharedStorage = new(8 * 1024 * 1024);
private ReadOnlySpan<byte> _bytes;
public ImString(ReadOnlySpan<byte> value)
{
_bytes = value; // avoid copying UTF8 literals
}
public ImString(ReadOnlySpan<byte> value, bool copy)
{
_bytes = copy ? SharedStorage.Append(value) : value;
}
public ImString(ReadOnlySpan<char> value)
{
_bytes = SharedStorage.Append(value);
}
public static implicit operator ImString(ReadOnlySpan<byte> value) => new(value);
public static implicit operator ImString(Span<byte> value) => new(value);
public static implicit operator ImString(ReadOnlySpan<char> value) => new(value);
public static implicit operator ImString(Span<char> value) => new(value);
public static implicit operator ImString(string value) => new(value);
public static implicit operator ImString(String8 value) => new(value, true); // String8 isn't fixed, so we need to copy it
public static implicit operator ImString(RefString8 value) => new(value.AsSpan());
public static implicit operator ImString(LString value) => new(value.Format());
public static implicit operator ImString(Ptr<byte> value) => new(Utf8.GetNullTerminatedSpan(value));
public static implicit operator ReadOnlySpan<byte>(in ImString s) => s._bytes;
public readonly ReadOnlySpan<byte> AsSpan() => _bytes;
/// for PInvoke
public ref readonly byte GetPinnableReference() => ref MemoryMarshal.GetReference(_bytes);
/// Convert to UTF16
public readonly Span<char> GetChars(Span<char> chars)
{
var len = Utf8.GetChars(_bytes, chars);
return chars[..len];
}
private static byte _forceNull;
/// Used to distinguish between "unset" vs "set to null" in optional arguments.
public static ImString Null => new ReadOnlySpan<byte>(ref _forceNull)[..0];
/// Returns a null-terminated empty string.
public static ImString Empty => ""u8;
/// Was a value set? Used to distinguish between "unset" vs "set to null" in optional arguments.
public readonly bool IsSet => !_bytes.IsNull();
/// Was a value set? Used to distinguish between "unset" vs "set to null" in optional arguments.
public readonly bool IsUnset => _bytes.IsNull();
/// Whether this represents a null string rather than an empty string.
/// Technically "IsDefault", but "IsNull" seems more intuitive.
public readonly bool IsNull() => _bytes.IsNull() || _bytes == Null;
public readonly bool IsEmpty => _bytes.IsEmpty;
// TODO: ensure byte count is always accurate / detect null-terminated byte spans
// TODO: evaluate character count vs byte count
public readonly int Length => _bytes.Length;
#region IUtf8SpanFormattable, ISpanFormattable, IFormattable
/// IUtf8SpanFormattable implementation
public bool TryFormat(
Span<byte> utf8Destination,
out int bytesWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider
)
{
if (_bytes.TryCopyTo(utf8Destination))
{
bytesWritten = _bytes.Length;
return true;
}
bytesWritten = 0;
return false;
}
/// ISpanFormattable implementation
public bool TryFormat(
Span<char> utf16Destination,
out int charsWritten,
ReadOnlySpan<char> format,
IFormatProvider? provider
)
{
return Utf8.ToUtf16(_bytes, utf16Destination, out _, out charsWritten) != OperationStatus.Done;
}
/// IFormattable implementation - useless but required for ISpanFormattable
string IFormattable.ToString(string? format, IFormatProvider? formatProvider) => ToString();
#endregion
}

View file

@ -0,0 +1,25 @@
using System.Runtime.InteropServices;
namespace Brutal.ImGuiApi;
static class InteropExtensions
{
/// Whether this span is unset rather than empty.
/// Technically "IsDefault", but "IsNull" seems more intuitive.
public static unsafe bool IsNull<T>(in this ReadOnlySpan<T> span)
where T : unmanaged
{
ref var spanRef = ref MemoryMarshal.GetReference(span);
fixed (T* spanPtr = &spanRef)
return spanPtr == null;
}
/// <inheritdoc cref="IsNull{T}(in System.ReadOnlySpan{T})"/>
public static unsafe bool IsNull<T>(in this Span<T> span)
where T : unmanaged
{
ref var spanRef = ref MemoryMarshal.GetReference(span);
fixed (T* spanPtr = &spanRef)
return spanPtr == null;
}
}