33
44#pragma warning disable CA2014 // Do not use stackalloc in loops
55
6+ using System . Buffers . Text ;
67using System . Text ;
78
89namespace 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}
0 commit comments