Skip to content

Commit

Permalink
Removed boxing and string allocations in DateTimeOffset/DateTime seri…
Browse files Browse the repository at this point in the history
…alization for legacy (but still frequently used) MessageTemplateTextFormatter
  • Loading branch information
epeshk authored and nblumhardt committed Aug 20, 2024
1 parent 8c82a50 commit 64fccfa
Showing 1 changed file with 37 additions and 0 deletions.
37 changes: 37 additions & 0 deletions src/Serilog/Events/ScalarValue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,43 @@ internal static void Render(object? value, TextWriter output, string? format = n
}
}

#if FEATURE_SPAN
internal static void Render<T>(T value, TextWriter output, string? format = null, IFormatProvider? formatProvider = null) where T : struct, IFormattable, ISpanFormattable
{
Guard.AgainstNull(output);

var custom = (ICustomFormatter?)formatProvider?.GetFormat(typeof(ICustomFormatter));
if (custom != null)
{
WriteWithCustomFormatter(value, output, format, formatProvider, custom);
return;
}

formatProvider ??= CultureInfo.InvariantCulture;
if (TryWriteSpanFormattable(value, output, format, formatProvider))
return;

output.Write(value.ToString(format, formatProvider));
}

static void WriteWithCustomFormatter<T>(T value, TextWriter output, string? format, IFormatProvider? formatProvider, ICustomFormatter custom) where T : struct, IFormattable
{
output.Write(custom.Format(format, value, formatProvider));
}

static bool TryWriteSpanFormattable<T>(T value, TextWriter output, string? format, IFormatProvider formatProvider) where T : struct, ISpanFormattable
{
Span<char> buffer = stackalloc char[36]; // large enough to fit ISO 8601 timestamp (DateTimeOffset.ToString("O"))
if (value.TryFormat(buffer, out var charsWritten, format, formatProvider))
{
output.Write(buffer[..charsWritten]);
return true;
}

return false;
}
#endif

/// <summary>
/// Determine if this instance is equal to <paramref name="obj"/>.
/// </summary>
Expand Down

0 comments on commit 64fccfa

Please sign in to comment.