mirror of
https://github.com/ahwootech/BRUTAL.git
synced 2026-11-26 04:58:24 +01:00
SOURCE DUMP v1
This commit is contained in:
parent
bd62d51ec9
commit
fb20299e9d
7 changed files with 768360 additions and 0 deletions
90
brutal.strings/Brutal.Strings/Unicode/Unicode.cs
Normal file
90
brutal.strings/Brutal.Strings/Unicode/Unicode.cs
Normal 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());
|
||||
}
|
||||
}
|
||||
202
brutal.strings/Brutal.Strings/Unicode/Utf.cs
Normal file
202
brutal.strings/Brutal.Strings/Unicode/Utf.cs
Normal file
|
|
@ -0,0 +1,202 @@
|
|||
using System.Diagnostics.Contracts;
|
||||
using System.Numerics;
|
||||
using System.Text;
|
||||
using Brutal.Extensions;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
public static class Utf<TChar>
|
||||
where TChar : unmanaged, IBinaryInteger<TChar> // IUtfChar<TChar> would be perfect, but is internal
|
||||
{
|
||||
static Utf()
|
||||
{
|
||||
if (typeof(TChar) != typeof(Char8) && typeof(TChar) != typeof(Char16))
|
||||
throw new NotSupportedException(
|
||||
$"Utf<TChar> supports only Char8 (byte) and Char16 (char): {typeof(TChar)} is unsupported."
|
||||
);
|
||||
}
|
||||
|
||||
/// Count the number of code units in <paramref name="value"/>.
|
||||
[Pure]
|
||||
public static int GetElementCount(String8View value)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char8) ? value.Length : Utf8.GetCharCount(value);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="GetElementCount(String8View)"/>
|
||||
[Pure]
|
||||
public static int GetElementCount(String16View value)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char16) ? value.Length : Utf8.GetByteCount(value);
|
||||
}
|
||||
|
||||
/// Copy/convert <paramref name="value"/> into <paramref name="destination"/>.
|
||||
public static void GetElements(String8View value, Span<TChar> destination)
|
||||
{
|
||||
if (typeof(TChar) == typeof(Char8))
|
||||
value.CopyTo(destination.AsChar8());
|
||||
else
|
||||
Utf8.GetChars(value, destination.AsChar16());
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="GetElements(String8View, Span{TChar})"/>
|
||||
public static void GetElements(String16View value, Span<TChar> destination)
|
||||
{
|
||||
if (typeof(TChar) == typeof(Char16))
|
||||
value.CopyTo(destination.AsChar16());
|
||||
else
|
||||
Utf8.GetBytes(value, destination.AsChar8());
|
||||
}
|
||||
|
||||
/// Try to copy/convert <paramref name="value"/> into <paramref name="destination"/>.
|
||||
public static bool TryGetElements(String8View value, Span<TChar> destination, out int elementsWritten)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char8)
|
||||
? value.TryCopyTo(destination.AsChar8(), out elementsWritten)
|
||||
: Utf8.TryGetChars(value, destination.AsChar16(), out elementsWritten);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="TryGetElements(String8View, Span{TChar}, out int)"/>
|
||||
public static bool TryGetElements(String16View value, Span<TChar> destination, out int elementsWritten)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char16)
|
||||
? value.TryCopyTo(destination.AsChar16(), out elementsWritten)
|
||||
: Utf8.TryGetBytes(value, destination.AsChar8(), out elementsWritten);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="TryGetElements(String8View, Span{TChar}, out int)"/>
|
||||
public static bool TryGetElements<TSource>(
|
||||
ReadOnlySpan<TSource> value,
|
||||
Span<TChar> destination,
|
||||
out int elementsWritten
|
||||
)
|
||||
where TSource : unmanaged, IBinaryInteger<TSource>
|
||||
{
|
||||
return typeof(TSource) == typeof(Char16)
|
||||
? TryGetElements(value.AsChar16(), destination, out elementsWritten)
|
||||
: TryGetElements(value.AsChar8(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Utf8.GetNullTerminatedSpan" />
|
||||
[Pure]
|
||||
public static ReadOnlySpan<TChar> GetNullTerminatedSpan(Ptr<TChar> first)
|
||||
{
|
||||
if (typeof(TChar) == typeof(Char8))
|
||||
{
|
||||
var bytes = Utf8.GetNullTerminatedSpan(first.Cast<Char8>());
|
||||
return Unsafe.BitCast<ReadOnlySpan<Char8>, ReadOnlySpan<TChar>>(bytes);
|
||||
}
|
||||
else
|
||||
{
|
||||
var chars = Utf16.GetNullTerminatedSpan(first.Cast<Char16>());
|
||||
return Unsafe.BitCast<ReadOnlySpan<Char16>, ReadOnlySpan<TChar>>(chars);
|
||||
}
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="string.ToCharArray()"/>
|
||||
/// <remarks>Allocates! Last resort helper for old string/array APIs - use spans when possible.</remarks>
|
||||
[Pure]
|
||||
public static TChar[] ToElementArray(string text)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char8)
|
||||
? Unsafe.As<TChar[]>(Encoding.UTF8.GetBytes(text))
|
||||
: Unsafe.As<TChar[]>(text.ToCharArray());
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Utf8.TryFormat{T}" />
|
||||
[Pure]
|
||||
public static bool TryFormat<T>(
|
||||
T value,
|
||||
Span<TChar> destination,
|
||||
out int elementsWritten,
|
||||
string? format = null,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char8)
|
||||
? Utf8.TryFormat(value, destination.AsChar8(), out elementsWritten, format, provider)
|
||||
: Utf16.TryFormat(value, destination.AsChar16(), out elementsWritten, format, provider);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Pad <paramref name="destination"/> to <paramref name="alignment"/> graphemes
|
||||
/// (right-align if positive, left-align if negative) by inserting/appending spaces.
|
||||
/// Returns false if <paramref name="destination"/> isn't big enough to fit the padded content
|
||||
/// (caller must grow + retry, or roll back).
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The buffer may need to hold more elements than <paramref name="alignment"/> alone suggests:
|
||||
/// graphemes can occupy multiple code units (é = 2 UTF-8 bytes; a combining mark adds its own unit),
|
||||
/// so the effective element target is alignment + (elementsWritten − graphemes).
|
||||
/// </remarks>
|
||||
/// <param name="destination">The buffer to align within</param>
|
||||
/// <param name="elementsWritten">How many code units were written to <paramref name="destination"/> - updated to include padding on success</param>
|
||||
/// <param name="alignment">How many graphemes to align by</param>
|
||||
public static bool TryAlign(Span<TChar> destination, ref int elementsWritten, int alignment)
|
||||
{
|
||||
if (alignment == 0)
|
||||
return true;
|
||||
|
||||
// Convert alignment from grapheme-count to code-unit-count.
|
||||
// IsAscii check is cheap, and avoids the much-rarer slow-path UAX-#29 segmentation.
|
||||
var written = destination[..elementsWritten];
|
||||
var graphemeOffset = IsAscii(written) ? 0 : elementsWritten - Unicode.GetGraphemeCount(written);
|
||||
alignment += graphemeOffset * Math.Sign(alignment);
|
||||
|
||||
return TryAppendOrInsertAlignmentIfNeeded(destination, ref elementsWritten, 0, alignment);
|
||||
}
|
||||
|
||||
private static bool IsAscii(ReadOnlySpan<TChar> span)
|
||||
{
|
||||
return typeof(TChar) == typeof(Char8) ? Ascii.IsValid(span.AsChar8()) : Ascii.IsValid(span.AsChar16());
|
||||
}
|
||||
|
||||
/// Source: https://github.com/dotnet/runtime/blob/f1874490fcf9ebaebff1ff5b9536742a286d145b/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs#L773
|
||||
public static bool TryAppendOrInsertAlignmentIfNeeded(
|
||||
Span<TChar> destination,
|
||||
ref int position,
|
||||
int startingPos,
|
||||
int alignment
|
||||
)
|
||||
{
|
||||
Debug.Assert(startingPos >= 0 && startingPos <= position);
|
||||
Debug.Assert(alignment != 0);
|
||||
|
||||
var elementsWritten = position - startingPos;
|
||||
|
||||
var leftAlign = false;
|
||||
if (alignment < 0)
|
||||
{
|
||||
leftAlign = true;
|
||||
alignment = -alignment;
|
||||
}
|
||||
|
||||
var paddingNeeded = alignment - elementsWritten;
|
||||
if (paddingNeeded <= 0)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
if (paddingNeeded <= destination.Length - position)
|
||||
{
|
||||
var space =
|
||||
typeof(TChar) == typeof(Char8)
|
||||
? Unsafe.BitCast<Char8, TChar>((Char8)' ')
|
||||
: Unsafe.BitCast<Char16, TChar>((Char16)' ');
|
||||
if (leftAlign)
|
||||
{
|
||||
destination.Slice(position, paddingNeeded).Fill(space);
|
||||
}
|
||||
else
|
||||
{
|
||||
destination.Slice(startingPos, elementsWritten).CopyTo(destination.Slice(startingPos + paddingNeeded));
|
||||
destination.Slice(startingPos, paddingNeeded).Fill(space);
|
||||
}
|
||||
|
||||
position += paddingNeeded;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
243
brutal.strings/Brutal.Strings/Unicode/Utf16.TryFormat.cs
Normal file
243
brutal.strings/Brutal.Strings/Unicode/Utf16.TryFormat.cs
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
using System.Buffers;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Globalization;
|
||||
using Brutal.Enums;
|
||||
using Brutal.Extensions;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
/*
|
||||
* KEEP IN SYNC with Utf8.TryFormat.cs - these two files mirror the same dispatch ladder and helper method
|
||||
* order so they diff cleanly. Differences are encoding-specific and noted inline:
|
||||
* - Utf8 needs TryFormat_ISpanFormattable (UTF-16 stack buffer → UTF-8 transcode), and TryAppend(ROS<char>, Span<byte>)
|
||||
* to transcode the string fast-path / ICustomFormatter / IFormattable fallback. Utf16 doesn't (ISpanFormattable
|
||||
* IS the native UTF-16 path; the equivalent TryAppend is just a CopyTo).
|
||||
* - Both encodings have bool / char extension methods, for symmetric reasons:
|
||||
* * bool: implements neither ISpanFormattable nor IUtf8SpanFormattable. BCL provides Boolean.TryFormat
|
||||
* for Span<char> but it's format-less (2-arg). Both extensions route through Utf{8,16}Formatter to
|
||||
* support the G/l format vocabulary (BCL provides Utf8Formatter; we provide Utf16Formatter,
|
||||
* deliberately diverging from the BCL's format-less char-side to keep our two encoding surfaces aligned).
|
||||
* * char: char.TryFormat is format-less / explicit on ISpanFormattable (boxes value types via the interface).
|
||||
* Both extensions inline the single-element write to dodge the box.
|
||||
*/
|
||||
|
||||
public static partial class Utf16
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to format <paramref name="value"/> as UTF-16 into <paramref name="destination"/>.
|
||||
/// Equivalent to <see cref="ISpanFormattable.TryFormat"/> but works for any <typeparamref name="T"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Dispatch priority:
|
||||
/// - <see cref="ICustomFormatter"/> (via <paramref name="provider"/>)
|
||||
/// - typed fast-paths: string, enum, primitive <see cref="ISpanFormattable"/> value-types
|
||||
/// - <see cref="ISpanFormattable"/>
|
||||
/// - <see cref="IFormattable"/>
|
||||
/// - <see cref="object.ToString()"/>
|
||||
/// The fast-paths short-circuit the cascade - same observable behavior, no boxing for value types.
|
||||
/// </remarks>
|
||||
/// <param name="value">The value to format. If null: write nothing and return true.</param>
|
||||
/// <param name="destination">Destination buffer for the UTF-16 output.</param>
|
||||
/// <param name="elementsWritten">Number of UTF-16 code units (chars) written on success.</param>
|
||||
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
|
||||
/// <param name="provider">Optional format provider. If it exposes <see cref="ICustomFormatter"/>, intercepts all other dispatch paths.</param>
|
||||
/// <typeparam name="T">The type of the value to format.</typeparam>
|
||||
/// <returns>True on success, false if <paramref name="destination"/> was too small.</returns>
|
||||
[Pure]
|
||||
public static bool TryFormat<T>(
|
||||
T value,
|
||||
Span<Char16> destination,
|
||||
out int elementsWritten,
|
||||
String16? format = null,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
// If there's a custom formatter, always use it.
|
||||
if (TryFormat_ICustomFormatter(value, destination, out elementsWritten, format, provider) is { } result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!typeof(T).IsValueType && value is null) // 'value is null' boxes in Debug - IsValueType pre-check folds it away
|
||||
{
|
||||
elementsWritten = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof(T) == typeof(string))
|
||||
{
|
||||
return TryAppend(Unsafe.As<T, string>(ref value).AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
#if NET
|
||||
// Special-case enums to avoid boxing them.
|
||||
if (typeof(T).IsEnum)
|
||||
{
|
||||
return Enum.TryFormatUnconstrained(value, destination, out elementsWritten, format);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if NET8_0_OR_GREATER
|
||||
// Value-type fast-paths: avoid the ~24 B box that `((ISpanFormattable)value).TryFormat()` would incur for an unconstrained generic T.
|
||||
// `typeof(T) == typeof(X)` folds at JIT specialization, so only the matching branch survives in each instantiation;
|
||||
// reference-type T pays nothing (all comparisons fold to false in the shared instantiation).
|
||||
// Same list as Utf8.TryFormat - every IUtf8SpanFormattable primitive also implements ISpanFormattable for Span<char>.
|
||||
if (typeof(T) == typeof(bool))
|
||||
return Unsafe.As<T, bool>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(char))
|
||||
return Unsafe.As<T, char>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(byte))
|
||||
return Unsafe.As<T, byte>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(sbyte))
|
||||
return Unsafe.As<T, sbyte>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(short))
|
||||
return Unsafe.As<T, short>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(ushort))
|
||||
return Unsafe.As<T, ushort>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(int))
|
||||
return Unsafe.As<T, int>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(uint))
|
||||
return Unsafe.As<T, uint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(long))
|
||||
return Unsafe.As<T, long>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(ulong))
|
||||
return Unsafe.As<T, ulong>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(nint))
|
||||
return Unsafe.As<T, nint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(nuint))
|
||||
return Unsafe.As<T, nuint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Int128))
|
||||
return Unsafe.As<T, Int128>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(UInt128))
|
||||
return Unsafe.As<T, UInt128>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Half))
|
||||
return Unsafe.As<T, Half>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(float))
|
||||
return Unsafe.As<T, float>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(double))
|
||||
return Unsafe.As<T, double>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(decimal))
|
||||
return Unsafe.As<T, decimal>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateTime))
|
||||
return Unsafe.As<T, DateTime>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateTimeOffset))
|
||||
return Unsafe
|
||||
.As<T, DateTimeOffset>(ref value)
|
||||
.TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(TimeSpan))
|
||||
return Unsafe.As<T, TimeSpan>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateOnly))
|
||||
return Unsafe.As<T, DateOnly>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(TimeOnly))
|
||||
return Unsafe.As<T, TimeOnly>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Guid))
|
||||
return Unsafe.As<T, Guid>(ref value).TryFormat(destination, out elementsWritten, format); // Guid's public TryFormat takes no provider (format is culture-invariant)
|
||||
if (typeof(T) == typeof(Bool8))
|
||||
return Unsafe.As<T, Bool8>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Bool32))
|
||||
return Unsafe.As<T, Bool32>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
#endif
|
||||
|
||||
/*
|
||||
* "is" check order: only matters for reference types (JIT-folded for value types)
|
||||
* The BCL checks were nested: IFormattable { ISpanFormattable },
|
||||
* we flattened to : ISpanFormattable, then IFormattable,
|
||||
* as ISpanFormattable types are the most common case in modern .NET / IFormattable is a rare fallback.
|
||||
*
|
||||
* Utf8 sibling has an extra IUtf8SpanFormattable layer ahead of ISpanFormattable; for Utf16 they
|
||||
* collapse into one - ISpanFormattable IS the native UTF-16 path, so no transcode helper is needed.
|
||||
*/
|
||||
|
||||
// If the value can format itself directly into our buffer, do so.
|
||||
if (value is ISpanFormattable)
|
||||
{
|
||||
return ((ISpanFormattable)value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
}
|
||||
|
||||
var s =
|
||||
value is IFormattable
|
||||
? ((IFormattable)value).ToString(format, provider) // If the value can ToString with the format / provider, get the resulting string, then append that.
|
||||
: value!.ToString(); // Fall back to a normal ToString and append that.
|
||||
return TryAppend(s.AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
/// Try to copy <paramref name="value"/> into <paramref name="destination"/>.
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool TryAppend(scoped String16View value, Span<Char16> destination, out int elementsWritten)
|
||||
{
|
||||
return value.TryCopyTo(destination, out elementsWritten);
|
||||
}
|
||||
|
||||
/// <returns>
|
||||
/// null: no custom formatter, normal dispatch should continue;
|
||||
/// otherwise, the formatter's result:
|
||||
/// true: success (even if the formatter failed or wrote nothing)
|
||||
/// false: the destination was too small.
|
||||
/// </returns>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static bool? TryFormat_ICustomFormatter<T>(
|
||||
T value,
|
||||
Span<Char16> destination,
|
||||
out int elementsWritten,
|
||||
String16? format,
|
||||
IFormatProvider? provider
|
||||
)
|
||||
{
|
||||
if (
|
||||
provider is null
|
||||
|| provider.GetType() == typeof(CultureInfo)
|
||||
|| // optimization to avoid GetFormat in the majority case
|
||||
provider.GetFormat(typeof(ICustomFormatter)) is not { } formatterObj
|
||||
)
|
||||
{
|
||||
elementsWritten = 0;
|
||||
return null; // not handled
|
||||
}
|
||||
|
||||
var formatter = (ICustomFormatter)formatterObj; // InvalidCastException if formatterObj is the wrong type
|
||||
if (formatter.Format(format, value, provider) is { } customFormatted)
|
||||
{
|
||||
return TryAppend(customFormatted.AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
elementsWritten = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// bool doesn't implement ISpanFormattable for some reason: this emulates it, for completeness.
|
||||
/// Also, this handles the G/l formats, which format-less bool.TryFormat() doesn't handle:
|
||||
/// https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.utf8formatter.tryformat?view=net-9.0#system-buffers-text-utf8formatter-tryformat(system-boolean-system-span((system-byte))-system-int32@-system-buffers-standardformat)
|
||||
/// Unknown formats fall back to the format-less behavior - matches C# string interpolation, which
|
||||
/// ignores the format for bool (no ISpanFormattable / IFormattable, so $"{flag:X}" yields "True").
|
||||
public static bool TryFormat(
|
||||
this bool value,
|
||||
Span<Char16> destination,
|
||||
out int elementsWritten,
|
||||
String16View format = default,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
return Utf16Formatter.TryFormat(value, destination, out elementsWritten, Utf8.ParseBoolFormat(format));
|
||||
}
|
||||
|
||||
/// char implements ISpanFormattable, but explicitly: here's a public extension, for completeness.
|
||||
/// Also, the BCL actually doesn't handle any formats; cast to ushort if you need formatting.
|
||||
public static bool TryFormat(
|
||||
this char value,
|
||||
Span<Char16> destination,
|
||||
out int elementsWritten,
|
||||
String16View format = default,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
if (destination.IsEmpty)
|
||||
{
|
||||
elementsWritten = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
destination[0] = value;
|
||||
elementsWritten = 1;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
25
brutal.strings/Brutal.Strings/Unicode/Utf16.cs
Normal file
25
brutal.strings/Brutal.Strings/Unicode/Utf16.cs
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
using System.Diagnostics.Contracts;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
/// <summary>UTF-16 / char-span counterpart of <see cref="Utf8"/>. Minimal surface for now.</summary>
|
||||
public static partial class Utf16
|
||||
{
|
||||
/// <summary>
|
||||
/// Count the number of chars in a null-terminated char array.
|
||||
/// </summary>
|
||||
[Pure]
|
||||
public static unsafe int GetCharCount(Ptr<Char16> chars)
|
||||
{
|
||||
return MemoryMarshal.CreateReadOnlySpanFromNullTerminated(chars).Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert a null-terminated char array to a <see cref="Span{T}"/> containing the chars up to the null terminator.
|
||||
/// </summary>
|
||||
[Pure]
|
||||
public static unsafe String16View GetNullTerminatedSpan(Ptr<Char16> chars)
|
||||
{
|
||||
return MemoryMarshal.CreateReadOnlySpanFromNullTerminated(chars);
|
||||
}
|
||||
}
|
||||
91
brutal.strings/Brutal.Strings/Unicode/Utf16Formatter.cs
Normal file
91
brutal.strings/Brutal.Strings/Unicode/Utf16Formatter.cs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
using System.Buffers;
|
||||
using System.Buffers.Text;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
public static class Utf16Formatter
|
||||
{
|
||||
/// <inheritdoc cref="Utf8Formatter.TryFormat(bool,System.Span{byte},out int,System.Buffers.StandardFormat)" />
|
||||
public static bool TryFormat(
|
||||
bool value,
|
||||
Span<Char16> destination,
|
||||
out int charsWritten,
|
||||
StandardFormat format = default
|
||||
)
|
||||
{
|
||||
var symbol = GetSymbolOrDefault(format, 'G');
|
||||
|
||||
if (value)
|
||||
{
|
||||
if (symbol == 'G')
|
||||
{
|
||||
if (!"True".TryCopyTo(destination))
|
||||
{
|
||||
goto BufferTooSmall;
|
||||
}
|
||||
}
|
||||
else if (symbol == 'l')
|
||||
{
|
||||
if (!"true".TryCopyTo(destination))
|
||||
{
|
||||
goto BufferTooSmall;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
goto BadFormat;
|
||||
}
|
||||
|
||||
charsWritten = 4;
|
||||
return true;
|
||||
}
|
||||
else
|
||||
{
|
||||
if (symbol == 'G')
|
||||
{
|
||||
if (!"False".TryCopyTo(destination))
|
||||
{
|
||||
goto BufferTooSmall;
|
||||
}
|
||||
}
|
||||
else if (symbol == 'l')
|
||||
{
|
||||
if (!"false".TryCopyTo(destination))
|
||||
{
|
||||
goto BufferTooSmall;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
goto BadFormat;
|
||||
}
|
||||
|
||||
charsWritten = 5;
|
||||
return true;
|
||||
}
|
||||
|
||||
BadFormat:
|
||||
throw new FormatException("BadFormatSpecifier");
|
||||
|
||||
BufferTooSmall:
|
||||
charsWritten = 0;
|
||||
return false;
|
||||
}
|
||||
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
static char GetSymbolOrDefault(in StandardFormat format, char defaultSymbol)
|
||||
{
|
||||
// This is equivalent to the line below, but it is written in such a way
|
||||
// that the JIT is able to perform more optimizations.
|
||||
//
|
||||
// return (format.IsDefault) ? defaultSymbol : format.Symbol;
|
||||
|
||||
var symbol = format.Symbol;
|
||||
if (symbol == default && format.Precision == default)
|
||||
{
|
||||
symbol = defaultSymbol;
|
||||
}
|
||||
|
||||
return symbol;
|
||||
}
|
||||
}
|
||||
318
brutal.strings/Brutal.Strings/Unicode/Utf8.TryFormat.cs
Normal file
318
brutal.strings/Brutal.Strings/Unicode/Utf8.TryFormat.cs
Normal file
|
|
@ -0,0 +1,318 @@
|
|||
using System.Buffers;
|
||||
using System.Buffers.Text;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Globalization;
|
||||
using System.Text;
|
||||
using Brutal.Enums;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
/*
|
||||
* KEEP IN SYNC with Utf16.TryFormat.cs - these two files mirror the same dispatch ladder and helper method
|
||||
* order so they diff cleanly. Differences are encoding-specific and noted inline:
|
||||
* - Utf8 needs TryFormat_ISpanFormattable (UTF-16 stack buffer → UTF-8 transcode), and TryAppend(ROS<char>, Span<byte>)
|
||||
* to transcode the string fast-path / ICustomFormatter / IFormattable fallback. Utf16 doesn't (ISpanFormattable
|
||||
* IS the native UTF-16 path; the equivalent TryAppend is just a CopyTo).
|
||||
* - Both encodings have bool / char extension methods, for symmetric reasons:
|
||||
* * bool: implements neither ISpanFormattable nor IUtf8SpanFormattable. BCL provides Boolean.TryFormat
|
||||
* for Span<char> but it's format-less (2-arg). Both extensions route through Utf{8,16}Formatter to
|
||||
* support the G/l format vocabulary (BCL provides Utf8Formatter; we provide Utf16Formatter,
|
||||
* deliberately diverging from the BCL's format-less char-side to keep our two encoding surfaces aligned).
|
||||
* * char: char.TryFormat is format-less / explicit on ISpanFormattable (boxes value types via the interface).
|
||||
* Both extensions inline the single-element write to dodge the box.
|
||||
*/
|
||||
|
||||
public static partial class Utf8
|
||||
{
|
||||
/// <summary>
|
||||
/// Tries to format <paramref name="value"/> as UTF-8 into <paramref name="destination"/>.
|
||||
/// Equivalent to <see cref="IUtf8SpanFormattable.TryFormat"/> but works for any <typeparamref name="T"/>.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Dispatch priority:
|
||||
/// - <see cref="ICustomFormatter"/> (via <paramref name="provider"/>)
|
||||
/// - typed fast-paths: string, enum, primitive <see cref="IUtf8SpanFormattable"/> value-types
|
||||
/// - <see cref="IUtf8SpanFormattable"/>
|
||||
/// - <see cref="ISpanFormattable"/>
|
||||
/// - <see cref="IFormattable"/>
|
||||
/// - <see cref="object.ToString()"/>
|
||||
/// The fast-paths short-circuit the cascade - same observable behavior, no boxing for value types.
|
||||
/// </remarks>
|
||||
/// <remarks>
|
||||
/// Source: https://github.com/dotnet/dotnet/blob/b0f34d51fccc69fd334253924abd8d6853fad7aa/src/runtime/src/libraries/System.Private.CoreLib/src/System/Text/Unicode/Utf8.cs#L485
|
||||
/// </remarks>
|
||||
/// <param name="value">The value to format. If null: write nothing and return true.</param>
|
||||
/// <param name="destination">Destination buffer for the UTF-8 output.</param>
|
||||
/// <param name="elementsWritten">Number of UTF-8 code units (bytes) written on success.</param>
|
||||
/// <param name="format">Optional format string, forwarded to the value's formatting interfaces.</param>
|
||||
/// <param name="provider">Optional format provider. If it exposes <see cref="ICustomFormatter"/>, intercepts all other dispatch paths.</param>
|
||||
/// <typeparam name="T">The type of the value to format.</typeparam>
|
||||
/// <returns>True on success, false if <paramref name="destination"/> was too small.</returns>
|
||||
[Pure]
|
||||
public static bool TryFormat<T>(
|
||||
T value,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16? format = null,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
// If there's a custom formatter, always use it.
|
||||
if (TryFormat_ICustomFormatter(value, destination, out elementsWritten, format, provider) is { } result)
|
||||
{
|
||||
return result;
|
||||
}
|
||||
|
||||
if (!typeof(T).IsValueType && value is null) // 'value is null' boxes in Debug - IsValueType pre-check folds it away
|
||||
{
|
||||
elementsWritten = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
if (typeof(T) == typeof(string))
|
||||
{
|
||||
return TryAppend(Unsafe.As<T, string>(ref value).AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
#if NET
|
||||
// Special-case enums to avoid boxing them.
|
||||
if (typeof(T).IsEnum)
|
||||
{
|
||||
// TODO https://github.com/dotnet/runtime/issues/81500:
|
||||
// Once Enum.TryFormat provides direct UTF8 support, use that here instead.
|
||||
return Enum.TryFormatUnconstrained(value, destination, out elementsWritten, format);
|
||||
}
|
||||
#endif
|
||||
|
||||
#if NET8_0_OR_GREATER
|
||||
// Value-type fast-paths: avoid the ~24 B box that `((IUtf8SpanFormattable)value).TryFormat()` would incur for an unconstrained generic T.
|
||||
// `typeof(T) == typeof(X)` folds at JIT specialization, so only the matching branch survives in each instantiation;
|
||||
// reference-type T pays nothing (all comparisons fold to false in the shared instantiation).
|
||||
// Covers every value type known to implement IUtf8SpanFormattable in Core (BCL primitives + Brutal's Bool8/Bool32).
|
||||
if (typeof(T) == typeof(bool))
|
||||
return Unsafe.As<T, bool>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(char))
|
||||
return Unsafe.As<T, char>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(byte))
|
||||
return Unsafe.As<T, byte>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(sbyte))
|
||||
return Unsafe.As<T, sbyte>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(short))
|
||||
return Unsafe.As<T, short>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(ushort))
|
||||
return Unsafe.As<T, ushort>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(int))
|
||||
return Unsafe.As<T, int>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(uint))
|
||||
return Unsafe.As<T, uint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(long))
|
||||
return Unsafe.As<T, long>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(ulong))
|
||||
return Unsafe.As<T, ulong>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(nint))
|
||||
return Unsafe.As<T, nint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(nuint))
|
||||
return Unsafe.As<T, nuint>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Int128))
|
||||
return Unsafe.As<T, Int128>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(UInt128))
|
||||
return Unsafe.As<T, UInt128>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Half))
|
||||
return Unsafe.As<T, Half>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(float))
|
||||
return Unsafe.As<T, float>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(double))
|
||||
return Unsafe.As<T, double>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(decimal))
|
||||
return Unsafe.As<T, decimal>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateTime))
|
||||
return Unsafe.As<T, DateTime>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateTimeOffset))
|
||||
return Unsafe
|
||||
.As<T, DateTimeOffset>(ref value)
|
||||
.TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(TimeSpan))
|
||||
return Unsafe.As<T, TimeSpan>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(DateOnly))
|
||||
return Unsafe.As<T, DateOnly>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(TimeOnly))
|
||||
return Unsafe.As<T, TimeOnly>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Guid))
|
||||
return Unsafe.As<T, Guid>(ref value).TryFormat(destination, out elementsWritten, format); // Guid's public TryFormat takes no provider (format is culture-invariant)
|
||||
if (typeof(T) == typeof(Bool8))
|
||||
return Unsafe.As<T, Bool8>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
if (typeof(T) == typeof(Bool32))
|
||||
return Unsafe.As<T, Bool32>(ref value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
#endif
|
||||
|
||||
/*
|
||||
* "is" check order: only matters for reference types (JIT-folded for value types)
|
||||
* The BCL checks were nested: IFormattable { ISpanFormattable },
|
||||
* we flattened to : ISpanFormattable, then IFormattable,
|
||||
* as ISpanFormattable types are the most common case in modern .NET / IFormattable is a rare fallback.
|
||||
*
|
||||
* nested: IU8 -> IForm { ISpan } flat: IU8 -> ISpan -> IForm
|
||||
* IUtf8SpanFormattable 1 (hit) 1 (hit)
|
||||
* ISpanFormattable 3 (fail, pass, pass) 2 (fail, pass)
|
||||
* IFormattable 3 (fail, pass, fail) 3 (fail, fail, pass)
|
||||
* neither 2 (fail, fail) 3 (fail, fail, fail)
|
||||
*/
|
||||
|
||||
// If the value can format itself directly into our buffer, do so.
|
||||
if (value is IUtf8SpanFormattable)
|
||||
{
|
||||
return ((IUtf8SpanFormattable)value).TryFormat(destination, out elementsWritten, format, provider);
|
||||
}
|
||||
|
||||
// If the value can format itself directly into a UTF16 buffer, do so, then transcode.
|
||||
if (value is ISpanFormattable)
|
||||
{
|
||||
return TryFormat_ISpanFormattable(value, destination, out elementsWritten, format, provider);
|
||||
}
|
||||
|
||||
var s =
|
||||
value is IFormattable
|
||||
? ((IFormattable)value).ToString(format, provider) // If the value can ToString with the format / provider, get the resulting string, then append that.
|
||||
: value!.ToString(); // Fall back to a normal ToString and append that.
|
||||
return TryAppend(s.AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
/// Convert <paramref name="value"/> from UTF-16 to UTF-8 into <paramref name="destination"/>.
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool TryAppend(scoped String16View value, Span<Char8> destination, out int elementsWritten)
|
||||
{
|
||||
return TryGetBytes(value, destination, out elementsWritten);
|
||||
}
|
||||
|
||||
/// <returns>
|
||||
/// null: no custom formatter, normal dispatch should continue;
|
||||
/// otherwise, the formatter's result:
|
||||
/// true: success (even if the formatter failed or wrote nothing)
|
||||
/// false: the destination was too small.
|
||||
/// </returns>
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
private static bool? TryFormat_ICustomFormatter<T>(
|
||||
T value,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16? format,
|
||||
IFormatProvider? provider
|
||||
)
|
||||
{
|
||||
if (
|
||||
provider is null
|
||||
|| provider.GetType() == typeof(CultureInfo)
|
||||
|| // optimization to avoid GetFormat in the majority case
|
||||
provider.GetFormat(typeof(ICustomFormatter)) is not { } formatterObj
|
||||
)
|
||||
{
|
||||
elementsWritten = 0;
|
||||
return null; // not handled
|
||||
}
|
||||
|
||||
var formatter = (ICustomFormatter)formatterObj; // InvalidCastException if formatterObj is the wrong type
|
||||
if (formatter.Format(format, value, provider) is { } customFormatted)
|
||||
{
|
||||
return TryAppend(customFormatted.AsSpan(), destination, out elementsWritten);
|
||||
}
|
||||
|
||||
elementsWritten = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Expects <paramref name="value"/> to be <see cref="ISpanFormattable"/>,
|
||||
/// and formats it into a temporary UTF-16 stack buffer, then converts to UTF-8.
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
private static bool TryFormat_ISpanFormattable<T>(
|
||||
T value,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16View format,
|
||||
IFormatProvider? provider
|
||||
)
|
||||
{
|
||||
Debug.Assert(value is ISpanFormattable);
|
||||
|
||||
Span<Char16> utf16 = stackalloc Char16[256];
|
||||
return ((ISpanFormattable)value).TryFormat(utf16, out var charsWritten, format, provider)
|
||||
? TryAppend(utf16[..charsWritten], destination, out elementsWritten)
|
||||
: GrowAndAppendFormatted(value, utf16.Length, destination, out elementsWritten, format, provider);
|
||||
|
||||
[MethodImpl(MethodImplOptions.NoInlining)]
|
||||
static bool GrowAndAppendFormatted(
|
||||
T value,
|
||||
int length,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16View format,
|
||||
IFormatProvider? provider
|
||||
)
|
||||
{
|
||||
Debug.Assert(value is ISpanFormattable);
|
||||
|
||||
while (true)
|
||||
{
|
||||
var newLength = length * 2;
|
||||
if ((uint)newLength > Array.MaxLength)
|
||||
{
|
||||
newLength =
|
||||
length == Array.MaxLength
|
||||
? Array.MaxLength + 1 // force OOM
|
||||
: Array.MaxLength;
|
||||
}
|
||||
|
||||
length = newLength;
|
||||
|
||||
var array = ArrayPool<Char16>.Shared.Rent(length);
|
||||
try
|
||||
{
|
||||
if (((ISpanFormattable)value).TryFormat(array, out var charsWritten, format, provider))
|
||||
{
|
||||
return TryAppend(array.AsSpan(0, charsWritten), destination, out elementsWritten);
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
ArrayPool<Char16>.Shared.Return(array);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Matches BCL interpolator behavior: falls back to the format-less behavior if the format is unknown.
|
||||
internal static StandardFormat ParseBoolFormat(String16View format)
|
||||
{
|
||||
return StandardFormat.TryParse(format, out var result) && result.Symbol is '\0' or 'G' or 'l'
|
||||
? result
|
||||
: default;
|
||||
}
|
||||
|
||||
/// bool doesn't implement IUtf8SpanFormattable for some reason: this emulates it, for completeness.
|
||||
/// Also, this handles the G/l formats, which non-UTF8 formatting doesn't handle:
|
||||
/// https://learn.microsoft.com/en-us/dotnet/api/system.buffers.text.utf8formatter.tryformat?view=net-9.0#system-buffers-text-utf8formatter-tryformat(system-boolean-system-span((system-byte))-system-int32@-system-buffers-standardformat)
|
||||
/// Unknown formats fall back to the format-less behavior - matches C# string interpolation, which
|
||||
/// ignores the format for bool (no ISpanFormattable / IFormattable, so $"{flag:X}" yields "True").
|
||||
public static bool TryFormat(
|
||||
this bool value,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16View format = default,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
return Utf8Formatter.TryFormat(value, destination, out elementsWritten, ParseBoolFormat(format));
|
||||
}
|
||||
|
||||
/// char implements IUtf8SpanFormattable, but explicitly: here's a public extension, for completeness.
|
||||
/// Also, the BCL actually doesn't handle any formats; cast to ushort if you need formatting.
|
||||
public static bool TryFormat(
|
||||
this char value,
|
||||
Span<Char8> destination,
|
||||
out int elementsWritten,
|
||||
String16View format = default,
|
||||
IFormatProvider? provider = null
|
||||
)
|
||||
{
|
||||
return TryGetBytes([value], destination, out elementsWritten);
|
||||
}
|
||||
}
|
||||
395
brutal.strings/Brutal.Strings/Unicode/Utf8.cs
Normal file
395
brutal.strings/Brutal.Strings/Unicode/Utf8.cs
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
using System.Buffers;
|
||||
using System.Diagnostics.Contracts;
|
||||
using System.Text;
|
||||
using Brutal.Collections.Experimental;
|
||||
using SystemUtf8 = System.Text.Unicode.Utf8;
|
||||
|
||||
namespace Brutal.Strings;
|
||||
|
||||
/// <summary>
|
||||
/// Combination of <see cref="System.Text.Unicode.Utf8"/> and <see cref="System.Text.Encoding.UTF8"/> for common UTF-8 operations.
|
||||
/// </summary>
|
||||
public static partial class Utf8
|
||||
{
|
||||
/// <summary>
|
||||
/// Count the number of bytes in a null-terminated byte array.
|
||||
/// </summary>
|
||||
[Pure]
|
||||
public static unsafe int GetByteCount(Ptr<Char8> bytes)
|
||||
{
|
||||
return MemoryMarshal.CreateReadOnlySpanFromNullTerminated(bytes).Length;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Convert a null-terminated byte array to a <see cref="Span{T}"/> containing the bytes up to the null terminator.
|
||||
/// </summary>
|
||||
[Pure]
|
||||
public static unsafe String8View GetNullTerminatedSpan(Ptr<Char8> bytes)
|
||||
{
|
||||
return MemoryMarshal.CreateReadOnlySpanFromNullTerminated(bytes);
|
||||
}
|
||||
|
||||
/// Evaluate length from the null-terminator, if found - strlen() equivalent.
|
||||
[Pure]
|
||||
public static int EvaluateLength(String8View utf8Buffer)
|
||||
{
|
||||
var length = utf8Buffer.IndexOf((Char8)0);
|
||||
return length != -1 ? length : utf8Buffer.Length;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(String8View, Span{Char16})"/>
|
||||
/// <remarks>Usage:<code>
|
||||
/// using (Utf8.GetChars(value, stackalloc Char16[256], out var chars))
|
||||
/// {
|
||||
/// // ... use "chars" here
|
||||
/// }
|
||||
/// </code></remarks>
|
||||
/// <param name="value">The value to decode</param>
|
||||
/// <param name="stackBuffer">A temporary buffer, typically stack-allocated; if too small, will rent an array.</param>
|
||||
/// <param name="chars">The decoded UTF16 characters</param>
|
||||
/// <returns>Scratch handle; dispose to return any rented array to the pool.</returns>
|
||||
[Pure]
|
||||
public static ScratchSpan<Char16> GetChars(String8View value, Span<Char16> stackBuffer, out Span<Char16> chars)
|
||||
{
|
||||
var scratch = new ScratchSpan<Char16>(GetCharCount(value), stackBuffer, out chars);
|
||||
GetChars(value, chars);
|
||||
return scratch;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(String16View, Span{Char8})"/>
|
||||
/// <remarks>Usage:<code>
|
||||
/// using (Utf8.GetBytes(value, stackalloc Char8[256], out var bytes))
|
||||
/// {
|
||||
/// // ... use "bytes" here
|
||||
/// }
|
||||
/// </code></remarks>
|
||||
/// <param name="value">The value to encode</param>
|
||||
/// <param name="stackBuffer">A temporary buffer, typically stack-allocated; if too small, will rent an array.</param>
|
||||
/// <param name="bytes">The encoded UTF8 bytes</param>
|
||||
/// <returns>Scratch handle; dispose to return any rented array to the pool.</returns>
|
||||
[Pure]
|
||||
public static ScratchSpan<Char8> GetBytes(String16View value, Span<Char8> stackBuffer, out Span<Char8> bytes)
|
||||
{
|
||||
var scratch = new ScratchSpan<Char8>(GetByteCount(value), stackBuffer, out bytes);
|
||||
GetBytes(value, bytes);
|
||||
return scratch;
|
||||
}
|
||||
}
|
||||
|
||||
// System.Text.Unicode.Utf8
|
||||
public static partial class Utf8
|
||||
{
|
||||
/// <inheritdoc cref="SystemUtf8.FromUtf16(String16View, Span{Char8}, out int, out int, bool, bool)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static System.Buffers.OperationStatus FromUtf16(
|
||||
String16View source,
|
||||
Span<Char8> destination,
|
||||
out int charsRead,
|
||||
out int bytesWritten,
|
||||
bool replaceInvalidSequences = true,
|
||||
bool isFinalBlock = true
|
||||
)
|
||||
{
|
||||
return SystemUtf8.FromUtf16(
|
||||
source,
|
||||
destination,
|
||||
out charsRead,
|
||||
out bytesWritten,
|
||||
replaceInvalidSequences,
|
||||
isFinalBlock
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SystemUtf8.ToUtf16(String8View, Span{Char16}, out int, out int, bool, bool)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static System.Buffers.OperationStatus ToUtf16(
|
||||
String8View source,
|
||||
Span<Char16> destination,
|
||||
out int bytesRead,
|
||||
out int charsWritten,
|
||||
bool replaceInvalidSequences = true,
|
||||
bool isFinalBlock = true
|
||||
)
|
||||
{
|
||||
return SystemUtf8.ToUtf16(
|
||||
source,
|
||||
destination,
|
||||
out bytesRead,
|
||||
out charsWritten,
|
||||
replaceInvalidSequences,
|
||||
isFinalBlock
|
||||
);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SystemUtf8.TryWrite(Span{Char8}, ref System.Text.Unicode.Utf8.TryWriteInterpolatedStringHandler, out int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool TryWrite(
|
||||
Span<Char8> destination,
|
||||
[InterpolatedStringHandlerArgument(nameof(destination))]
|
||||
ref SystemUtf8.TryWriteInterpolatedStringHandler handler,
|
||||
out int bytesWritten
|
||||
)
|
||||
{
|
||||
return SystemUtf8.TryWrite(destination, ref handler, out bytesWritten);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SystemUtf8.TryWrite(Span{Char8}, IFormatProvider?, ref System.Text.Unicode.Utf8.TryWriteInterpolatedStringHandler, out int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool TryWrite(
|
||||
Span<Char8> destination,
|
||||
IFormatProvider? provider,
|
||||
[InterpolatedStringHandlerArgument(nameof(destination), nameof(provider))]
|
||||
ref SystemUtf8.TryWriteInterpolatedStringHandler handler,
|
||||
out int bytesWritten
|
||||
)
|
||||
{
|
||||
return SystemUtf8.TryWrite(destination, provider, ref handler, out bytesWritten);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="SystemUtf8.IsValid(String8View)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool IsValid(String8View value)
|
||||
{
|
||||
return SystemUtf8.IsValid(value);
|
||||
}
|
||||
}
|
||||
|
||||
// System.Text.Encoding.UTF8
|
||||
public static partial class Utf8
|
||||
{
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(Char16[])"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetByteCount(Char16[] chars)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(chars, 0, chars.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetByteCount(string str)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(str);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(Char16[], int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetByteCount(Char16[] chars, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(chars, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(string, int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetByteCount(string s, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(s, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(Char16*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe int GetByteCount(Ptr<Char16> chars, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(chars, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetByteCount(String16View)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetByteCount(String16View chars)
|
||||
{
|
||||
return Encoding.UTF8.GetByteCount(chars);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(Char16[])"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char8[] GetBytes(Char16[] chars)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(chars);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(Char16[], int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char8[] GetBytes(Char16[] chars, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(chars, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(Char16[], int, int, Char8[], int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetBytes(Char16[] chars, int charIndex, int charCount, Char8[] bytes, int byteIndex)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(chars, charIndex, charCount, bytes, byteIndex);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(string)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char8[] GetBytes(string s)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(s);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(string, int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char8[] GetBytes(string s, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(s, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(string, int, int, Char8[], int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetBytes(string s, int charIndex, int charCount, Char8[] bytes, int byteIndex)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(s, charIndex, charCount, bytes, byteIndex);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(Char16*, int, Char8*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe int GetBytes(Ptr<Char16> chars, int charCount, Ptr<Char8> bytes, int byteCount)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(chars, charCount, bytes, byteCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetBytes(String16View, Span{Char8})"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetBytes(String16View chars, Span<Char8> bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetBytes(chars, bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.TryGetBytes(String16View, Span{Char8}, out int)"/>
|
||||
/// <remarks>
|
||||
/// Routed through <see cref="FromUtf16"/>, which is single-pass and alloc-free.
|
||||
/// Avoid using <see cref="Encoding.TryGetBytes"/> which allocates (an EncoderFallbackBuffer)
|
||||
/// when <paramref name="bytes"/> is too small.
|
||||
/// </remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool TryGetBytes(String16View chars, Span<Char8> bytes, out int bytesWritten)
|
||||
{
|
||||
if (FromUtf16(chars, bytes, out _, out bytesWritten) == OperationStatus.Done)
|
||||
return true;
|
||||
bytesWritten = 0; // return 0 on failure, matching Encoding.TryGetBytes (no partial count)
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetCharCount(Char8[])"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetCharCount(Char8[] bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetCharCount(bytes, 0, bytes.Length);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetCharCount(Char8[], int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetCharCount(Char8[] bytes, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetCharCount(bytes, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetCharCount(Char8*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe int GetCharCount(Ptr<Char8> bytes, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetCharCount(bytes, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetCharCount(String8View)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetCharCount(String8View bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetCharCount(bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(Char8[])"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char16[] GetChars(Char8[] bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetChars(bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(Char8[], int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static Char16[] GetChars(Char8[] bytes, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetChars(bytes, index, count);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(Char8[], int, int, Char16[], int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetChars(Char8[] bytes, int byteIndex, int byteCount, Char16[] chars, int charIndex)
|
||||
{
|
||||
return Encoding.UTF8.GetChars(bytes, byteIndex, byteCount, chars, charIndex);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(Char8*, int, Char16*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe int GetChars(Ptr<Char8> bytes, int byteCount, Ptr<Char16> chars, int charCount)
|
||||
{
|
||||
return Encoding.UTF8.GetChars(bytes, byteCount, chars, charCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetChars(String8View, Span{Char16})"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetChars(String8View bytes, Span<Char16> chars)
|
||||
{
|
||||
return Encoding.UTF8.GetChars(bytes, chars);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.TryGetChars(String8View, Span{Char16}, out int)"/>
|
||||
/// <remarks><inheritdoc cref="TryGetBytes(String16View, Span{Char8}, out int)" path="/remarks"/></remarks>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static bool TryGetChars(String8View bytes, Span<Char16> chars, out int charsWritten)
|
||||
{
|
||||
if (ToUtf16(bytes, chars, out _, out charsWritten) == OperationStatus.Done)
|
||||
return true;
|
||||
charsWritten = 0; // return 0 on failure, matching Encoding.TryGetBytes (no partial count)
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetString(Char8*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe string GetString(Ptr<Char8> bytes, int byteCount)
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes, byteCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetString(Char8*, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static unsafe string GetString(Ptr<Char8> bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes, GetByteCount(bytes));
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetString(String8View)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string GetString(String8View bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetMaxByteCount(int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetMaxByteCount(int charCount)
|
||||
{
|
||||
return Encoding.UTF8.GetMaxByteCount(charCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetMaxCharCount(int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static int GetMaxCharCount(int byteCount)
|
||||
{
|
||||
return Encoding.UTF8.GetMaxCharCount(byteCount);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetString(Char8[])"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string GetString(Char8[] bytes)
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes);
|
||||
}
|
||||
|
||||
/// <inheritdoc cref="Encoding.GetString(Char8[], int, int)"/>
|
||||
[MethodImpl(MethodImplOptions.AggressiveInlining)]
|
||||
public static string GetString(Char8[] bytes, int index, int count)
|
||||
{
|
||||
return Encoding.UTF8.GetString(bytes, index, count);
|
||||
}
|
||||
}
|
||||
Loading…
Reference in a new issue