Skip to content

Commit

Permalink
Merge pull request #7 from Cysharp/hadashiA/fix-missing-tryformat
Browse files Browse the repository at this point in the history
Fix missing TryFormat
  • Loading branch information
neuecc authored Nov 16, 2023
2 parents 3be7e5a + e41d058 commit c6e469e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 26 deletions.
49 changes: 24 additions & 25 deletions src/Utf8StringInterpolation/Shims.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,36 @@

#pragma warning disable CA2014 // Do not use stackalloc in loops

using System.Buffers.Text;
using System.Text;

namespace Utf8StringInterpolation
{
#if !NET8_0_OR_GREATER

internal static partial class Shims
{
public static bool TryFormat(this char value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
{
#if NET6_0_OR_GREATER
return new Rune(value).TryEncodeToUtf8(utf8Destination, out bytesWritten);
#else
Span<char> xs = stackalloc char[1];
xs[0] = value;

var count = Encoding.UTF8.GetByteCount(xs);
if (utf8Destination.Length < count)
{
bytesWritten = 0;
return false;
}
else
{
bytesWritten = Encoding.UTF8.GetBytes(xs, utf8Destination);
return true;
}
#endif
}

#if !NET8_0_OR_GREATER
public static bool TryFormat(this DateTime value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
{
Span<char> charDest = stackalloc char[256];
Expand Down Expand Up @@ -91,29 +113,6 @@ public static bool TryFormat(this TimeSpan value, Span<byte> utf8Destination, ou
bytesWritten = Encoding.UTF8.GetBytes(charDest.Slice(0, charWritten), utf8Destination);
return true;
}

public static bool TryFormat(this char value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
{
#if NET6_0_OR_GREATER
return new Rune(value).TryEncodeToUtf8(utf8Destination, out bytesWritten);
#else
Span<char> xs = stackalloc char[1];
xs[0] = value;

var count = Encoding.UTF8.GetByteCount(xs);
if (utf8Destination.Length < count)
{
bytesWritten = 0;
return false;
}
else
{
bytesWritten = Encoding.UTF8.GetBytes(xs, utf8Destination);
return true;
}
#endif
}
}

#endif
}
1 change: 0 additions & 1 deletion src/Utf8StringInterpolation/Utf8String.AppendFormatted.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using System.Buffers;
using System.Buffers.Text;
using System.Runtime.CompilerServices;
using System.Text;

namespace Utf8StringInterpolation;

Expand Down

0 comments on commit c6e469e

Please # to comment.