csharp-sdk/src/Common/Polyfills/System/Text/EncodingExtensions.cs
Copilot 80b1ad21d7
Use ReadOnlyMemory<byte> for binary data to eliminate UTF-16 transcoding (#1070)
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: stephentoub <2642209+stephentoub@users.noreply.github.com>
Co-authored-by: ericstj <8918108+ericstj@users.noreply.github.com>
Co-authored-by: Eric StJohn <ericstj@microsoft.com>
2026-02-19 14:08:05 -08:00

50 lines
1.2 KiB
C#

// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
#if !NET
namespace System.Text;
internal static class EncodingExtensions
{
/// <summary>
/// Gets the number of bytes required to encode the specified characters.
/// </summary>
public static int GetByteCount(this Encoding encoding, ReadOnlySpan<char> chars)
{
if (chars.IsEmpty)
{
return 0;
}
unsafe
{
fixed (char* charsPtr = chars)
{
return encoding.GetByteCount(charsPtr, chars.Length);
}
}
}
/// <summary>
/// Encodes the specified characters into the specified byte span.
/// </summary>
public static int GetBytes(this Encoding encoding, ReadOnlySpan<char> chars, Span<byte> bytes)
{
if (chars.IsEmpty)
{
return 0;
}
unsafe
{
fixed (char* charsPtr = chars)
fixed (byte* bytesPtr = bytes)
{
return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length);
}
}
}
}
#endif