EncodingExtensions
Represents extension method for Encoding data type.
using DotNext.Buffers;
using System;
using System.Runtime.CompilerServices;
using System.Text;
namespace DotNext.Text
{
public static class EncodingExtensions
{
[System.Runtime.CompilerServices.Nullable(1)]
private static readonly UTF8Encoding Utf8WithoutPreamble = new UTF8Encoding(false);
[System.Runtime.CompilerServices.NullableContext(1)]
public static Encoding WithoutPreamble(this Encoding encoding)
{
if (!(encoding is UTF8Encoding))
return EncodingWithoutPreamble.Create(encoding);
return Utf8WithoutPreamble;
}
public static MemoryOwner<byte> GetBytes([System.Runtime.CompilerServices.Nullable(1)] this Encoding encoding, ReadOnlySpan<char> chars, [System.Runtime.CompilerServices.Nullable(2)] MemoryAllocator<byte> allocator = null)
{
MemoryOwner<byte> result;
if (chars.IsEmpty)
result = default(MemoryOwner<byte>);
else {
result = allocator.Invoke(encoding.GetByteCount(chars), true);
encoding.GetBytes(chars, result.Memory.Span);
}
return result;
}
public static MemoryOwner<char> GetChars([System.Runtime.CompilerServices.Nullable(1)] this Encoding encoding, ReadOnlySpan<byte> bytes, [System.Runtime.CompilerServices.Nullable(2)] MemoryAllocator<char> allocator = null)
{
MemoryOwner<char> result;
if (bytes.IsEmpty)
result = default(MemoryOwner<char>);
else {
result = allocator.Invoke(encoding.GetCharCount(bytes), true);
encoding.GetChars(bytes, result.Memory.Span);
}
return result;
}
}
}