From 9e29123d2e7aaa84f665599c07feb9fe6f512734 Mon Sep 17 00:00:00 2001 From: Daniel Cazzulino Date: Sat, 7 Dec 2024 12:07:00 -0300 Subject: [PATCH] Add IUtf8SpanFormattable template --- src/StructId.FunctionalTests/Functional.cs | 21 +++++++++++++++++++ src/StructId/Templates/Utf8SpanFormattable.cs | 12 +++++++++++ 2 files changed, 33 insertions(+) create mode 100644 src/StructId/Templates/Utf8SpanFormattable.cs diff --git a/src/StructId.FunctionalTests/Functional.cs b/src/StructId.FunctionalTests/Functional.cs index bbfbc25..8b4a84a 100644 --- a/src/StructId.FunctionalTests/Functional.cs +++ b/src/StructId.FunctionalTests/Functional.cs @@ -1,4 +1,5 @@ using System.Diagnostics.CodeAnalysis; +using System.Text; using Dapper; using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; @@ -140,6 +141,26 @@ public void StringIdDoesNotImplementISpanFormattable() Assert.IsNotAssignableFrom(WalletId.New("foo")); } + [Fact] + public void GuidImplementUtf8SpanFormattable() + { + var id = ProductId.New(); + + Assert.IsAssignableFrom(id); + + Span utf8Destination = new byte[36]; // Typical GUID length in string form + + if (id.TryFormat(utf8Destination, out int bytesWritten, default, null)) + { + var guid = new Guid(Encoding.UTF8.GetString(utf8Destination.Slice(0, bytesWritten))); + Assert.Equal(id.Value, guid); + } + else + { + Assert.Fail("TryFormat failed"); + } + } + public class Context : DbContext { public Context(DbContextOptions options) : base(options) { } diff --git a/src/StructId/Templates/Utf8SpanFormattable.cs b/src/StructId/Templates/Utf8SpanFormattable.cs new file mode 100644 index 0000000..51fe415 --- /dev/null +++ b/src/StructId/Templates/Utf8SpanFormattable.cs @@ -0,0 +1,12 @@ +// +#nullable enable + +using System; +using StructId; + +[TStructId] +file partial record struct Utf8SpanFormattable(IUtf8SpanFormattable Value) : IUtf8SpanFormattable +{ + public bool TryFormat(Span utf8Destination, out int bytesWritten, ReadOnlySpan format, IFormatProvider? provider) + => Value.TryFormat(utf8Destination, out bytesWritten, format, provider); +} \ No newline at end of file