MemoryAllocator
Represents interop layer between .NET memory pools
and MemoryAllocator<T>.
using System;
using System.Buffers;
using System.Runtime.CompilerServices;
namespace DotNext.Buffers
{
[System.Runtime.CompilerServices.NullableContext(1)]
[System.Runtime.CompilerServices.Nullable(0)]
public static class MemoryAllocator
{
private static MemoryOwner<T> Allocate<T>(this ArrayPool<T> pool, int length)
{
return new MemoryOwner<T>(pool, length);
}
public static MemoryAllocator<T> ToAllocator<[System.Runtime.CompilerServices.Nullable(2)] T>(this ArrayPool<T> pool)
{
return pool.Allocate<T>;
}
private static MemoryOwner<T> Allocate<T>(this MemoryPool<T> pool, int length)
{
return new MemoryOwner<T>(pool, length);
}
public static MemoryAllocator<T> ToAllocator<[System.Runtime.CompilerServices.Nullable(2)] T>(this MemoryPool<T> pool)
{
return pool.Allocate<T>;
}
private static MemoryOwner<T> Allocate<T>(this Func<int, IMemoryOwner<T>> provider, int length)
{
return new MemoryOwner<T>(provider, length);
}
public static MemoryAllocator<T> ToAllocator<[System.Runtime.CompilerServices.Nullable(2)] T>(this Func<int, IMemoryOwner<T>> provider)
{
return provider.Allocate<T>;
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.NullableContext(2)]
[return: System.Runtime.CompilerServices.Nullable(new byte[] {
0,
1
})]
public static MemoryOwner<T> Invoke<T>([System.Runtime.CompilerServices.Nullable(new byte[] {
2,
1
})] this MemoryAllocator<T> allocator, int length, bool exactSize)
{
MemoryOwner<T> result;
if (allocator == null)
result = Allocate<T>(length, exactSize);
else {
result = allocator(length);
if (exactSize)
result.Truncate(length);
else
result.Expand();
}
return result;
}
public static MemoryAllocator<T> CreateArrayAllocator<[System.Runtime.CompilerServices.Nullable(2)] T>()
{
return (int length) => new MemoryOwner<T>(GC.AllocateUninitializedArray<T>(length, false));
}
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[System.Runtime.CompilerServices.NullableContext(2)]
[return: System.Runtime.CompilerServices.Nullable(new byte[] {
0,
1
})]
public static MemoryOwner<T> Allocate<T>(int length, bool exactSize)
{
return new MemoryOwner<T>(ArrayPool<T>.Shared, length, exactSize);
}
}
}