Skip to content

Commit

Permalink
add Guid.TryFormat
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp committed Feb 13, 2024
1 parent c0f41c6 commit e888eae
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/Polyfill/Polyfill_TryFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,25 @@ public static bool TryFormat(this TimeSpan target, Span<char> destination, out i

return CopyToSpan(destination, out charsWritten, result);
}
/// <summary>
/// Tries to format the value of the current instance as UTF-8 into the provided span of bytes.
/// </summary>
[Link("https://learn.microsoft.com/en-us/dotnet/api/system.guid.tryformat#system-guid-tryformat(system-span((system-char))-system-int32@-system-readonlyspan((system-char)))")]
public static bool TryFormat(this Guid target, Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default)
{
string result;

if (format.Length == 0)
{
result = target.ToString(null);
}
else
{
result = target.ToString(format.ToString());
}

return CopyToSpan(destination, out charsWritten, result);
}

/// <summary>
/// Tries to format the value of the current instance into the provided span of characters.
Expand Down
11 changes: 11 additions & 0 deletions src/Tests/PolyfillTests_TryFormat.cs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,17 @@ public void TryFormatSingle()
Assert.AreEqual(buffer.Length, written);
}

[Test]
public void TryFormatGuid()
{
var value = new Guid("97008c2d-2114-4396-ae19-392c8e6f8f1b");
Span<char> buffer = stackalloc char[36];
var result = value.TryFormat(buffer, out var written);
Assert.True(result);
Assert.AreEqual("97008c2d-2114-4396-ae19-392c8e6f8f1b", buffer.ToString());
Assert.AreEqual(buffer.Length, written);
}

[Test]
public void TryFormatDouble()
{
Expand Down

0 comments on commit e888eae

Please sign in to comment.