Skip to content

Commit

Permalink
expose Encoding.GetBytes(ReadOnlySpan,Span) in unsafe (#274)
Browse files Browse the repository at this point in the history
  • Loading branch information
SimonCropp authored Jan 3, 2025
1 parent 762db83 commit c686808
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
15 changes: 14 additions & 1 deletion src/Polyfill/Polyfill_Encoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -47,12 +47,13 @@ public static int GetByteCount(this Encoding target, ReadOnlySpan<char> chars)
#endif
#endif

#if AllowUnsafeBlocks && !NETCOREAPP2_1_OR_GREATER
#if !NETCOREAPP2_1_OR_GREATER
/// <summary>When overridden in a derived class, encodes into a span of bytes a set of characters from the specified read-only span.</summary>
/// <param name="chars">The span containing the set of characters to encode.</param>
/// <param name="bytes">The byte span to hold the encoded bytes.</param>
/// <returns>The number of encoded bytes.</returns>
//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<char> chars, Span<byte> bytes)
{
if (target is null)
Expand All @@ -66,7 +67,19 @@ public static unsafe int GetBytes(this Encoding target, ReadOnlySpan<char> chars
return target.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
}
}
#else
public static int GetBytes(this Encoding target, ReadOnlySpan<char> chars, Span<byte> 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
/// <summary>When overridden in a derived class, decodes all the bytes in the specified byte span into a string.</summary>
Expand Down
4 changes: 0 additions & 4 deletions src/Tests/PolyfillTests_Encoding.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -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
}

0 comments on commit c686808

Please sign in to comment.