From c686808bbbb4fdf0638b53a13c55116aa371abbf Mon Sep 17 00:00:00 2001 From: Simon Cropp Date: Fri, 3 Jan 2025 21:59:39 +1100 Subject: [PATCH] expose Encoding.GetBytes(ReadOnlySpan,Span) in unsafe (#274) --- src/Polyfill/Polyfill_Encoding.cs | 15 ++++++++++++++- src/Tests/PolyfillTests_Encoding.cs | 4 ---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/src/Polyfill/Polyfill_Encoding.cs b/src/Polyfill/Polyfill_Encoding.cs index 1bf3ef1..cbf1e59 100644 --- a/src/Polyfill/Polyfill_Encoding.cs +++ b/src/Polyfill/Polyfill_Encoding.cs @@ -47,12 +47,13 @@ public static int GetByteCount(this Encoding target, ReadOnlySpan chars) #endif #endif -#if AllowUnsafeBlocks && !NETCOREAPP2_1_OR_GREATER +#if !NETCOREAPP2_1_OR_GREATER /// When overridden in a derived class, encodes into a span of bytes a set of characters from the specified read-only span. /// The span containing the set of characters to encode. /// The byte span to hold the encoded bytes. /// The number of encoded bytes. //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))) +#if AllowUnsafeBlocks public static unsafe int GetBytes(this Encoding target, ReadOnlySpan chars, Span bytes) { if (target is null) @@ -66,7 +67,19 @@ public static unsafe int GetBytes(this Encoding target, ReadOnlySpan chars return target.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); } } +#else + public static int GetBytes(this Encoding target, ReadOnlySpan chars, Span bytes) + { + if (target is null) + { + throw new ArgumentNullException(nameof(target)); + } + var result = target.GetBytes(chars.ToArray()); + result.CopyTo(bytes); + return result.Length; + } +#endif #endif #if !NETCOREAPP2_1_OR_GREATER /// When overridden in a derived class, decodes all the bytes in the specified byte span into a string. diff --git a/src/Tests/PolyfillTests_Encoding.cs b/src/Tests/PolyfillTests_Encoding.cs index e5d8e00..24355c5 100644 --- a/src/Tests/PolyfillTests_Encoding.cs +++ b/src/Tests/PolyfillTests_Encoding.cs @@ -18,7 +18,6 @@ public void Encoding_GetString() var result = Encoding.UTF8.GetString(array); Assert.AreEqual("value", result); } -#if AllowUnsafeBlocks [Test] public void Encoding_GetBytes() @@ -27,14 +26,11 @@ public void Encoding_GetBytes() var chars = "Hello, World!".AsSpan(); var bytes = new byte[encoding.GetByteCount(chars)].AsSpan(); - // Act var byteCount = encoding.GetBytes(chars, bytes); - // Assert Assert.AreEqual(encoding.GetByteCount(chars), byteCount); Assert.AreEqual(encoding.GetBytes("Hello, World!"), bytes.ToArray()); } -#endif #endif } \ No newline at end of file