Skip to content

Commit c686808

Browse files
authored
expose Encoding.GetBytes(ReadOnlySpan,Span) in unsafe (#274)
1 parent 762db83 commit c686808

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

src/Polyfill/Polyfill_Encoding.cs

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,12 +47,13 @@ public static int GetByteCount(this Encoding target, ReadOnlySpan<char> chars)
4747
#endif
4848
#endif
4949

50-
#if AllowUnsafeBlocks && !NETCOREAPP2_1_OR_GREATER
50+
#if !NETCOREAPP2_1_OR_GREATER
5151
/// <summary>When overridden in a derived class, encodes into a span of bytes a set of characters from the specified read-only span.</summary>
5252
/// <param name="chars">The span containing the set of characters to encode.</param>
5353
/// <param name="bytes">The byte span to hold the encoded bytes.</param>
5454
/// <returns>The number of encoded bytes.</returns>
5555
//Link: https://learn.microsoft.com/en-us/dotnet/api/system.text.encoding.getbytes#system-text-encoding-getbytes(system-readonlyspan((system-char))-system-span((system-byte)))
56+
#if AllowUnsafeBlocks
5657
public static unsafe int GetBytes(this Encoding target, ReadOnlySpan<char> chars, Span<byte> bytes)
5758
{
5859
if (target is null)
@@ -66,7 +67,19 @@ public static unsafe int GetBytes(this Encoding target, ReadOnlySpan<char> chars
6667
return target.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
6768
}
6869
}
70+
#else
71+
public static int GetBytes(this Encoding target, ReadOnlySpan<char> chars, Span<byte> bytes)
72+
{
73+
if (target is null)
74+
{
75+
throw new ArgumentNullException(nameof(target));
76+
}
6977

78+
var result = target.GetBytes(chars.ToArray());
79+
result.CopyTo(bytes);
80+
return result.Length;
81+
}
82+
#endif
7083
#endif
7184
#if !NETCOREAPP2_1_OR_GREATER
7285
/// <summary>When overridden in a derived class, decodes all the bytes in the specified byte span into a string.</summary>

src/Tests/PolyfillTests_Encoding.cs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,6 @@ public void Encoding_GetString()
1818
var result = Encoding.UTF8.GetString(array);
1919
Assert.AreEqual("value", result);
2020
}
21-
#if AllowUnsafeBlocks
2221

2322
[Test]
2423
public void Encoding_GetBytes()
@@ -27,14 +26,11 @@ public void Encoding_GetBytes()
2726
var chars = "Hello, World!".AsSpan();
2827
var bytes = new byte[encoding.GetByteCount(chars)].AsSpan();
2928

30-
// Act
3129
var byteCount = encoding.GetBytes(chars, bytes);
3230

33-
// Assert
3431
Assert.AreEqual(encoding.GetByteCount(chars), byteCount);
3532
Assert.AreEqual(encoding.GetBytes("Hello, World!"), bytes.ToArray());
3633
}
3734

38-
#endif
3935
#endif
4036
}

0 commit comments

Comments
 (0)