DotNext by .NET Foundation and Contributors

<PackageReference Include="DotNext" Version="4.12.1" />

 MemoryOwnerWrapper<T>

using System; using System.Buffers; using System.Runtime.InteropServices; namespace DotNext.Buffers { [StructLayout(LayoutKind.Auto)] internal struct MemoryOwnerWrapper<T> : IBufferWriter<T> { private readonly MemoryAllocator<T> allocator; internal MemoryOwner<T> Buffer; internal MemoryOwnerWrapper(MemoryAllocator<T> allocator) { this.allocator = allocator; Buffer = default(MemoryOwner<T>); } private void Allocate(int length) { Buffer = ((allocator == null) ? new MemoryOwner<T>(ArrayPool<T>.Shared, length) : allocator(length)); } Span<T> IBufferWriter<T>.GetSpan(int sizeHint) { Allocate(sizeHint); return Buffer.Span; } Memory<T> IBufferWriter<T>.GetMemory(int sizeHint) { Allocate(sizeHint); return Buffer.Memory; } void IBufferWriter<T>.Advance(int count) { if (count == 0) Buffer.Dispose(); else Buffer.Truncate(count); } } }