Initial commit

This commit is contained in:
dennisarfan 2025-07-30 07:30:00 +07:00
commit ef3b7d68fb
30 changed files with 1568 additions and 0 deletions

View file

@ -0,0 +1,29 @@
using System.Buffers;
namespace StitchATon2.Infra.Buffers;
public class ArrayOwner<T> : IBuffer<T> where T : unmanaged
{
private readonly ArrayPool<T> _owner;
private readonly T[] _buffer;
public ArrayOwner(ArrayPool<T> owner, int size)
{
_owner = owner;
_buffer = owner.Rent(size);
}
~ArrayOwner() => Dispose();
public void Dispose()
{
_owner.Return(_buffer);
GC.SuppressFinalize(this);
}
public ref T this[int index] => ref _buffer[index];
public Span<T> Span => _buffer;
public T[] Array => _buffer;
}

8
Infra/Buffers/IBuffer.cs Normal file
View file

@ -0,0 +1,8 @@
namespace StitchATon2.Infra.Buffers;
public interface IBuffer<T> : IDisposable where T : unmanaged
{
ref T this[int index] { get; }
Span<T> Span { get; }
}

View file

@ -0,0 +1,15 @@
using System.Buffers;
namespace StitchATon2.Infra.Buffers;
public static class MemoryAllocator
{
public static IBuffer<T> Allocate<T>(int count) where T : unmanaged
=> new UnmanagedMemory<T>(count);
public static IMemoryOwner<T> AllocateManaged<T>(int count)
=> MemoryPool<T>.Shared.Rent(count);
public static ArrayOwner<T> AllocateArray<T>(int count) where T : unmanaged
=> new(ArrayPool<T>.Shared, count);
}

View file

@ -0,0 +1,28 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
namespace StitchATon2.Infra.Buffers;
internal sealed unsafe class UnmanagedMemory<T> : IBuffer<T> where T : unmanaged
{
private readonly void* _pointer;
private readonly int _count;
public ref T this[int index] => ref Unsafe.AsRef<T>((T*)_pointer + index); // *((T*)_pointer + index);
public Span<T> Span => new(_pointer, _count);
public UnmanagedMemory(int count)
{
_pointer = NativeMemory.Alloc((nuint)count, (nuint)Unsafe.SizeOf<T>());
_count = count;
}
~UnmanagedMemory() => Dispose();
public void Dispose()
{
NativeMemory.Free(_pointer);
GC.SuppressFinalize(this);
}
}