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