using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StitchATon2.Infra.Buffers;
///
/// Provide non-thread safe anti GC contiguous memory.
///
///
internal sealed unsafe class UnmanagedMemory : IBuffer where T : unmanaged
{
private readonly T* _pointer;
private readonly int _count;
private bool _disposed;
public ref T this[int index] => ref Unsafe.AsRef(_pointer + index);
public Span Span => new(_pointer, _count);
public UnmanagedMemory(int count)
{
_pointer = (T*)NativeMemory.Alloc((nuint)count, (nuint)Unsafe.SizeOf());
_count = count;
}
~UnmanagedMemory() => Dispose();
public void Dispose()
{
if (!_disposed)
{
NativeMemory.Free(_pointer);
GC.SuppressFinalize(this);
_disposed = true;
}
}
}