Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
}