Skip to content

Commit c6e469e

Browse files
authored
Merge pull request #7 from Cysharp/hadashiA/fix-missing-tryformat
Fix missing TryFormat
2 parents 3be7e5a + e41d058 commit c6e469e

File tree

2 files changed

+24
-26
lines changed

2 files changed

+24
-26
lines changed

src/Utf8StringInterpolation/Shims.cs

Lines changed: 24 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -3,14 +3,36 @@
33

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

6+
using System.Buffers.Text;
67
using System.Text;
78

89
namespace Utf8StringInterpolation
910
{
10-
#if !NET8_0_OR_GREATER
11-
1211
internal static partial class Shims
1312
{
13+
public static bool TryFormat(this char value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
14+
{
15+
#if NET6_0_OR_GREATER
16+
return new Rune(value).TryEncodeToUtf8(utf8Destination, out bytesWritten);
17+
#else
18+
Span<char> xs = stackalloc char[1];
19+
xs[0] = value;
20+
21+
var count = Encoding.UTF8.GetByteCount(xs);
22+
if (utf8Destination.Length < count)
23+
{
24+
bytesWritten = 0;
25+
return false;
26+
}
27+
else
28+
{
29+
bytesWritten = Encoding.UTF8.GetBytes(xs, utf8Destination);
30+
return true;
31+
}
32+
#endif
33+
}
34+
35+
#if !NET8_0_OR_GREATER
1436
public static bool TryFormat(this DateTime value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
1537
{
1638
Span<char> charDest = stackalloc char[256];
@@ -91,29 +113,6 @@ public static bool TryFormat(this TimeSpan value, Span<byte> utf8Destination, ou
91113
bytesWritten = Encoding.UTF8.GetBytes(charDest.Slice(0, charWritten), utf8Destination);
92114
return true;
93115
}
94-
95-
public static bool TryFormat(this char value, Span<byte> utf8Destination, out int bytesWritten, string? format, IFormatProvider? formatProvider)
96-
{
97-
#if NET6_0_OR_GREATER
98-
return new Rune(value).TryEncodeToUtf8(utf8Destination, out bytesWritten);
99-
#else
100-
Span<char> xs = stackalloc char[1];
101-
xs[0] = value;
102-
103-
var count = Encoding.UTF8.GetByteCount(xs);
104-
if (utf8Destination.Length < count)
105-
{
106-
bytesWritten = 0;
107-
return false;
108-
}
109-
else
110-
{
111-
bytesWritten = Encoding.UTF8.GetBytes(xs, utf8Destination);
112-
return true;
113-
}
114116
#endif
115-
}
116117
}
117-
118-
#endif
119118
}

src/Utf8StringInterpolation/Utf8String.AppendFormatted.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
using System.Buffers;
22
using System.Buffers.Text;
33
using System.Runtime.CompilerServices;
4-
using System.Text;
54

65
namespace Utf8StringInterpolation;
76

0 commit comments

Comments
 (0)