SOURCE DUMP v1

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

View file

@ -0,0 +1,188 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Brutal.Strings.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class PreferString8OverloadAnalyzer : DiagnosticAnalyzer
{
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
[Resources.PreferU8OverloadBrutalCore0011];
public override void Initialize(AnalysisContext context)
{
context.EnableConcurrentExecution();
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(startContext =>
{
// Early-exit if ReadOnlySpan<T> is unavailable (e.g. netstandard2.0 without System.Memory)
var readOnlySpan = startContext.Compilation.GetTypeByMetadataName("System.ReadOnlySpan`1");
if (readOnlySpan is null)
return;
var analyzer = new PreferString8OverloadCompilationAnalyzer(startContext.Compilation, readOnlySpan);
startContext.RegisterOperationAction(analyzer.Analyze, OperationKind.Argument, OperationKind.Conversion);
});
}
}
/*
* Follow the guidelines frmo RS1008 (https://dotnetrules.com):
* Avoid storing per-compilation data into the fields of a diagnostic analyzer
* Instance of a diagnostic analyzer might outlive the lifetime of compilation.
* Hence, storing per-compilation data, such as symbols, into the fields of a diagnostic analyzer might cause stale compilations to stay alive and cause memory leaks.
* Instead, you should store this data on a separate type instantiated in a compilation start action, registered using 'AnalysisContext.RegisterCompilationStartAction' API.
* An instance of this type will be created per-compilation and it won't outlive compilation's lifetime, hence avoiding memory leaks.
*/
class PreferString8OverloadCompilationAnalyzer(Compilation compilation, INamedTypeSymbol readOnlySpan)
{
private readonly INamedTypeSymbol _readOnlySpanByte = readOnlySpan.Construct(
compilation.GetSpecialType(SpecialType.System_Byte)
);
private bool IsString8(ITypeSymbol type) => compilation.HasImplicitConversion(_readOnlySpanByte, type);
private static bool IsString16(ITypeSymbol type) => type.SpecialType == SpecialType.System_String;
/// Is method <paramref name="overload"/> a compatible replacement for <paramref name="method"/>?
private bool IsCompatible(OperationAnalysisContext context, IMethodSymbol method, IMethodSymbol overload)
{
/*
* We want to err on the side of caution: only suggest using an overload if it is _strictly_ identical:
* - same kind/generic-ness etc.
* - same type parameters (same constraints etc.)
* - same parameters (except for string/String8 of course)
*
* We won't suggest overloads with (type) parameters that _could_ be compatible through conversion, type constraints etc.
*/
if (method.MethodKind != overload.MethodKind)
return false;
var isGeneric = method.IsGenericMethod;
if (isGeneric != overload.IsGenericMethod)
return false;
// ignore self
if (SymbolEqualityComparer.IncludeNullability.Equals(isGeneric ? method.OriginalDefinition : method, overload))
return false;
// is the overload accessible from the call site?
if (!compilation.IsSymbolAccessibleWithin(overload, context.ContainingSymbol.ContainingType))
return false;
if (isGeneric)
{
// compare type parameters
if (!method.TypeParameters.SequenceEqual(overload.TypeParameters, IsCompatible))
return false;
}
// compare parameters
if (!method.Parameters.SequenceEqual(overload.Parameters, (a, b) => IsCompatible(a.Type, b.Type)))
return false;
return true;
}
/// Is type <paramref name="overloadParamType"/> a compatible replacement for <paramref name="methodParamType"/>?
private bool IsCompatible(ITypeSymbol methodParamType, ITypeSymbol overloadParamType)
{
if (SymbolEqualityComparer.IncludeNullability.Equals(methodParamType, overloadParamType))
return true;
if (IsString16(methodParamType) && IsString8(overloadParamType))
return true;
return false;
}
/// Are type parameters a and b compatible?
private static bool IsCompatible(ITypeParameterSymbol a, ITypeParameterSymbol b)
{
return a.AllowsRefLikeType == b.AllowsRefLikeType
&& a.HasConstructorConstraint == b.HasConstructorConstraint
&& a.HasNotNullConstraint == b.HasNotNullConstraint
&& a.HasReferenceTypeConstraint == b.HasReferenceTypeConstraint
&& a.HasUnmanagedTypeConstraint == b.HasUnmanagedTypeConstraint
&& a.HasValueTypeConstraint == b.HasValueTypeConstraint
&& a.Variance == b.Variance
&& Utility.SequenceEqual(a.ConstraintTypes, b.ConstraintTypes, SymbolEqualityComparer.IncludeNullability);
}
public void Analyze(OperationAnalysisContext context)
{
switch (context.Operation)
{
case IArgumentOperation argumentOp:
{
var parameter = argumentOp.Parameter;
if (parameter == null)
break;
// is the current argument a string literal?
if (!IsString16(parameter.Type) || argumentOp.Value.Syntax is not LiteralExpressionSyntax)
break;
if (argumentOp.Parent is not IInvocationOperation parent)
break;
// does the method have an overload that takes a UTF8 string instead?
var method = parent.TargetMethod;
var overloads = method.ContainingType.GetMembers(method.Name).OfType<IMethodSymbol>();
var overload = overloads.FirstOrDefault(o => IsCompatible(context, method, o));
if (overload == null)
break;
// suggest using a UTF8 literal instead of a string
var message = overload.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat);
ReportDiagnostic(message);
break;
}
case IConversionOperation conversionOp:
{
if (conversionOp.OperatorMethod == null)
break;
// are we converting from a string literal?
if (conversionOp.Operand is not ILiteralOperation { Type.SpecialType: SpecialType.System_String })
break;
// is the target type assignable from UTF8?
var targetType = conversionOp.Type;
if (targetType == null || !IsString8(targetType))
break;
// find the actual conversion method - only for displaying to the user / debugging
var conversions = targetType
.GetMembers()
.OfType<IMethodSymbol>()
.Where(m => m.MethodKind == MethodKind.Conversion);
var overload = conversions.FirstOrDefault(m => IsString8(m.Parameters[0].Type));
var message =
overload?.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)
?? $"{targetType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)} implicit conversion from UTF8";
// suggest using a UTF8 literal instead of a string
ReportDiagnostic(message);
break;
}
}
void ReportDiagnostic(string message)
{
var diagnostic = Diagnostic.Create(
Resources.PreferU8OverloadBrutalCore0011,
context.Operation.Syntax.GetLocation(),
message
);
context.ReportDiagnostic(diagnostic);
}
}
}

View file

@ -0,0 +1,37 @@
using Microsoft.CodeAnalysis;
namespace Brutal.Strings.Analyzers;
public static class Resources
{
public static readonly DiagnosticDescriptor BrutalCore0001 = new(
"BRUTALCORE0001",
"Avoid calling ToString on (ReadOnly)Span<byte>",
"ToString() on a span does not convert the contents to a string, did you mean to use ToString16?",
"Intent",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Span<byte>.ToString() does not decode the bytes to a string."
);
public const string BrutalCore0001Suggestion = "Use .ToString16()";
public static readonly DiagnosticDescriptor BrutalCore0002 = new(
"BRUTALCORE0002",
"Avoid calling ToString on (ReadOnly)Span<T> where T is not string or byte",
"ToString() on a span does not convert the contents to a string, did you mean to use a different method?",
"Intent",
DiagnosticSeverity.Warning,
isEnabledByDefault: true,
description: "Span<T>.ToString() does not decode the content to a string."
);
public static readonly DiagnosticDescriptor PreferU8OverloadBrutalCore0011 = new(
"BRUTALCORE0011",
"Prefer using a UTF8 string",
"Prefer using a UTF8 string: {0}",
"Usage",
DiagnosticSeverity.Warning,
isEnabledByDefault: true
);
public const string PreferU8OverloadBrutalCore0011Suggestion = "Append u8 to the string literal";
}

View file

@ -0,0 +1,70 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Operations;
namespace Brutal.Strings.Analyzers;
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class SpanToStringAnalyzer : DiagnosticAnalyzer
{
// Keep in mind: you have to list your rules here.
public override ImmutableArray<DiagnosticDescriptor> SupportedDiagnostics { get; } =
[Resources.BrutalCore0001, Resources.BrutalCore0002];
public override void Initialize(AnalysisContext context)
{
// You must call this method to avoid analyzing generated code.
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
// You must call this method to enable the Concurrent Execution.
context.EnableConcurrentExecution();
// Monitor (method) invocations
context.RegisterOperationAction(AnalyzeInvocation, OperationKind.Invocation);
}
private static void AnalyzeInvocation(OperationAnalysisContext context)
{
var invocation = (IInvocationOperation)context.Operation;
var method = invocation.TargetMethod;
if (method.Name != "ToString")
return;
var type = method.ContainingType;
if (type.TypeArguments.Length != 1)
return;
var compilation = context.Compilation;
var spanType = compilation.GetTypeByMetadataName("System.Span`1");
var readOnlySpanType = compilation.GetTypeByMetadataName("System.ReadOnlySpan`1");
// no need for IncludeNullability as all types we're testing are value types, and spans can't be nullable
var comparer = SymbolEqualityComparer.Default;
if (
!comparer.Equals(type.OriginalDefinition, spanType)
&& !comparer.Equals(type.OriginalDefinition, readOnlySpanType)
)
return;
var typeArg = type.TypeArguments[0];
var charType = compilation.GetTypeByMetadataName("System.Char");
var byteType = compilation.GetTypeByMetadataName("System.Byte");
// Span<char>.ToString() is ok
if (comparer.Equals(typeArg, charType))
return;
var rule = comparer.Equals(typeArg, byteType) ? Resources.BrutalCore0001 : Resources.BrutalCore0002;
var invocationSyntax = (InvocationExpressionSyntax)invocation.Syntax;
var memberAccess = (MemberAccessExpressionSyntax)invocationSyntax.Expression;
var methodSyntax = memberAccess.Name;
var diagnostic = Diagnostic.Create(rule, methodSyntax.GetLocation());
context.ReportDiagnostic(diagnostic);
}
}

View file

@ -0,0 +1,17 @@
using System.Collections.Immutable;
using Microsoft.CodeAnalysis;
public static class Utility
{
public static bool SequenceEqual<TSymbol>(
ImmutableArray<TSymbol> a,
ImmutableArray<TSymbol> b,
SymbolEqualityComparer comparer
)
where TSymbol : class, ISymbol
{
var aUp = ImmutableArray<ISymbol>.CastUp(a);
var bUp = ImmutableArray<ISymbol>.CastUp(b);
return aUp.SequenceEqual(bUp, comparer);
}
}

View file

@ -0,0 +1,74 @@
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Brutal.Strings.Analyzers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(PreferString8OverloadFixProvider)), Shared]
public class PreferString8OverloadFixProvider : CodeFixProvider
{
private static readonly string DiagnosticId = Resources.PreferU8OverloadBrutalCore0011.Id;
private const string Suggestion = Resources.PreferU8OverloadBrutalCore0011Suggestion;
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [DiagnosticId];
public override FixAllProvider GetFixAllProvider() => WellKnownFixAllProviders.BatchFixer;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
// We link only one diagnostic and assume there is only one diagnostic in the context.
var diagnostic = context.Diagnostics.Single();
// 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename.
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Get the root of Syntax Tree that contains the highlighted diagnostic.
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find SyntaxNode corresponding to the diagnostic.
var diagnosticNode = root?.FindNode(diagnosticSpan);
// We expect a string literal (argument or conversion)
var literal = diagnosticNode switch
{
ArgumentSyntax { Expression: LiteralExpressionSyntax literalArg } => literalArg,
LiteralExpressionSyntax literalConversion => literalConversion,
_ => null,
};
if (literal == null)
return;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Suggestion,
createChangedSolution: c => FixAsync(context.Document, literal, c),
equivalenceKey: nameof(DiagnosticId)
),
diagnostic
);
}
private static async Task<Solution> FixAsync(
Document document,
LiteralExpressionSyntax stringLiteral,
CancellationToken cancellationToken
)
{
var root = await document.GetSyntaxRootAsync(cancellationToken);
if (root == null)
return document.Project.Solution;
// change from "literal" to "literal"u8
var token = stringLiteral.Token;
var u8Token = SyntaxFactoryExtensions.Utf8Literal(token.Text + "u8", token.ValueText);
var u8Literal = SyntaxFactory.LiteralExpression(SyntaxKind.Utf8StringLiteralExpression, u8Token);
var newRoot = root.ReplaceNode(stringLiteral, u8Literal);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument.Project.Solution;
}
}

View file

@ -0,0 +1,67 @@
using System.Collections.Immutable;
using System.Composition;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp;
namespace Brutal.Strings.Analyzers;
[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(SpanToStringFixProvider)), Shared]
public class SpanToStringFixProvider : CodeFixProvider
{
// Specify the diagnostic IDs of analyzers that are expected to be linked.
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = [Resources.BrutalCore0001.Id];
// If you don't need the 'fix all' behaviour, return null.
public override FixAllProvider? GetFixAllProvider() => null;
public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
// We link only one diagnostic and assume there is only one diagnostic in the context.
var diagnostic = context.Diagnostics.Single();
// 'SourceSpan' of 'Location' is the highlighted area. We're going to use this area to find the 'SyntaxNode' to rename.
var diagnosticSpan = diagnostic.Location.SourceSpan;
// Get the root of Syntax Tree that contains the highlighted diagnostic.
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
// Find SyntaxNode corresponding to the diagnostic.
var diagnosticNode = root?.FindNode(diagnosticSpan)!;
// Register a code action that will invoke the fix.
context.RegisterCodeFix(
CodeAction.Create(
title: Resources.BrutalCore0001Suggestion,
createChangedSolution: c => FixToStringAsync(context.Document, diagnosticNode, c),
equivalenceKey: nameof(Resources.BrutalCore0001.Id)
),
diagnostic
);
}
/// <summary>
/// Executed on the quick fix action raised by the user.
/// </summary>
/// <param name="document">Affected source file.</param>
/// <param name="methodName">The syntax node that we found in 'RegisterCodeFixesAsync'.</param>
/// <param name="cancellationToken">Any fix is cancellable by the user, so we should support the cancellation token.</param>
/// <returns>Clone of the solution with updates: renamed class.</returns>
private static async Task<Solution> FixToStringAsync(
Document document,
SyntaxNode methodName,
CancellationToken cancellationToken
)
{
// change from "ReadOnlySpan<byte>.ToString()" to "ReadOnlySpan<byte>.ToString16()"
var root = await document.GetSyntaxRootAsync(cancellationToken);
if (root == null)
return document.Project.Solution;
var newName = SyntaxFactory.IdentifierName("ToString16");
var newRoot = root.ReplaceNode(methodName, newName);
var newDocument = document.WithSyntaxRoot(newRoot);
return newDocument.Project.Solution;
}
}

View file

@ -0,0 +1,26 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
namespace Brutal.Strings.Analyzers;
using static SyntaxFactory;
// TODO: move this to a shared package...
public static class SyntaxFactoryExtensions
{
/// <inheritdoc cref="Utf8Literal(string,string)" />
public static SyntaxToken Utf8Literal(string value)
{
return Utf8Literal(SymbolDisplay.FormatLiteral(value, quote: true) + "u8", value);
}
/// <summary>
/// Creates a token with kind Utf8StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Utf8Literal(string text, string value)
{
return Token(SyntaxTriviaList.Empty, SyntaxKind.Utf8StringLiteralToken, text, value, SyntaxTriviaList.Empty);
}
}

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

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