using System; using System.Runtime.InteropServices; using System.Text; namespace ComputeSharp.D2D1.NetStandard.System.Text; /// /// A polyfill type that mirrors some methods from on .NET 5. /// internal static class EncodingExtensions { /// /// Encodes into a span of bytes a set of characters from the specified read-only span. /// /// The input instance to use. /// The span containing the set of characters to encode. /// The byte span to hold the encoded bytes. /// The number of encoded bytes. public static unsafe int GetBytes(this Encoding encoding, ReadOnlySpan chars, Span bytes) { fixed (char* charsPtr = &MemoryMarshal.GetReference(chars)) fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) { return encoding.GetBytes(charsPtr, chars.Length, bytesPtr, bytes.Length); } } /// /// Decodes a text from a sequence of bytes. /// /// The input instance to use. /// The byte span that holds the encoded bytes. /// The resulting text. public static unsafe string GetString(this Encoding encoding, ReadOnlySpan bytes) { fixed (byte* bytesPtr = &MemoryMarshal.GetReference(bytes)) { return encoding.GetString(bytesPtr, bytes.Length); } } }