// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Runtime.InteropServices;
namespace System.Runtime.CompilerServices;
///
/// Provides a handler used by the language compiler to format interpolated strings into character spans.
///
[InterpolatedStringHandler]
internal ref struct TryWriteFormatInterpolatedStringHandler
{
///
/// The destination buffer.
///
private readonly Span destination;
///
/// The format to use to print individual values to the target buffer.
///
private readonly ReadOnlySpan format;
///
/// The value of , as a .
///
private string? formatAsString;
///
/// Optional provider to pass to calls.
///
private readonly IFormatProvider? formatProvider;
///
/// The number of characters written to .
///
private int position;
///
/// Indicates whether all formatting operations have succeeded.
///
private bool success;
///
/// Whether provides an .
///
private readonly bool hasCustomFormatter;
///
/// Creates a handler used to write an interpolated string into a .
///
/// The number of constant characters outside of interpolation expressions in the interpolated string.
/// The number of interpolation expressions in the interpolated string.
/// The destination buffer.
/// The format to use, if available.
/// An object that supplies culture-specific formatting information.
/// Upon return, true if the destination may be long enough to support the formatting, or false if it won't be.
/// This is intended to be called only by compiler-generated code. Arguments are not validated as they'd otherwise be for members intended to be used directly.
public TryWriteFormatInterpolatedStringHandler(int literalLength, int formattedCount, Span destination, ReadOnlySpan format, IFormatProvider? formatProvider, out bool shouldAppend)
{
this.destination = destination;
this.format = format;
this.formatAsString = null;
this.formatProvider = formatProvider;
this.position = 0;
this.success = shouldAppend = destination.Length >= literalLength;
this.hasCustomFormatter = formatProvider is not null && FormatInterpolatedStringHandler.HasCustomFormatter(formatProvider);
}
///
/// Writes the specified interpolated string to the character span.
///
/// The span to which the interpolated string should be formatted.
/// The format to use, if available.
/// An object that supplies culture-specific formatting information.
/// The interpolated string.
/// The number of characters written to the span.
/// true if the entire interpolated string could be formatted successfully; otherwise, false.
public static bool TryWrite(
Span destination,
ReadOnlySpan format,
IFormatProvider? formatProvider,
[InterpolatedStringHandlerArgument("destination", "format", "formatProvider")] ref TryWriteFormatInterpolatedStringHandler handler,
out int charsWritten)
{
if (handler.success)
{
charsWritten = handler.position;
return true;
}
charsWritten = 0;
return false;
}
///
/// Writes the specified to the handler.
///
/// The to write.
/// Whether the value could be formatted to the span.
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public bool AppendLiteral(string value)
{
if (value.Length == 1)
{
Span destination = this.destination;
int pos = this.position;
if ((uint)pos < (uint)destination.Length)
{
destination[pos] = value[0];
this.position = pos + 1;
return true;
}
return Fail();
}
if (value.Length == 2)
{
Span destination = this.destination;
int pos = this.position;
if ((uint)pos < destination.Length - 1)
{
Unsafe.WriteUnaligned(
ref Unsafe.As(ref Unsafe.Add(ref MemoryMarshal.GetReference(destination), pos)),
#if NET6_0_OR_GREATER
Unsafe.ReadUnaligned(ref Unsafe.As(ref Unsafe.AsRef(in value.GetPinnableReference()))));
#else
Unsafe.ReadUnaligned(ref Unsafe.As(ref MemoryMarshal.GetReference(value.AsSpan()))));
#endif
this.position = pos + 2;
return true;
}
return Fail();
}
return AppendStringDirect(value);
}
///
/// Writes the specified string to the handler.
///
/// The string to write.
/// Whether the value could be appended to the span.
private bool AppendStringDirect(string value)
{
#if NET6_0_OR_GREATER
if (value.TryCopyTo(this.destination.Slice(this.position)))
#else
if (value.AsSpan().TryCopyTo(this.destination.Slice(this.position)))
#endif
{
this.position += value.Length;
return true;
}
return Fail();
}
///
/// Writes the specified value to the handler.
///
/// The value to write.
public bool AppendFormatted(T value)
#if NET6_0_OR_GREATER
where T : ISpanFormattable
#else
where T : IFormattable
#endif
{
if (this.hasCustomFormatter)
{
return AppendCustomFormatter(value, this.formatAsString ??= this.format.ToString());
}
#if NET6_0_OR_GREATER
if (value.TryFormat(this.destination.Slice(this.position), out int charsWritten, this.format, this.formatProvider))
{
this.position += charsWritten;
return true;
}
return Fail();
#else
return AppendStringDirect(value.ToString(this.formatAsString ??= this.format.ToString(), this.formatProvider));
#endif
}
///
/// Writes the specified value to the handler.
///
/// The value to write.
public bool AppendFormatted(string? value)
{
if (this.hasCustomFormatter)
{
return AppendCustomFormatter(value, format: null);
}
if (value is null)
{
return true;
}
#if NET6_0_OR_GREATER
if (value.TryCopyTo(this.destination.Slice(this.position)))
#else
if (value.AsSpan().TryCopyTo(this.destination.Slice(this.position)))
#endif
{
this.position += value.Length;
return true;
}
return Fail();
}
///
/// Formats the value using the custom formatter from the provider.
///
/// The value to write.
/// The format string.
[MethodImpl(MethodImplOptions.NoInlining)]
private bool AppendCustomFormatter(T value, string? format)
{
ICustomFormatter? formatter = (ICustomFormatter?)this.formatProvider?.GetFormat(typeof(ICustomFormatter));
if (formatter is not null && formatter.Format(format, value, this.formatProvider) is string customFormatted)
{
return AppendStringDirect(customFormatted);
}
return true;
}
///
/// Marks formatting as having failed and returns false.
///
private bool Fail()
{
this.success = false;
return false;
}
}