feat(memory): add generic IMemoryAllocator and MemoryPool
Refactored Arena, DynamicArena, FreeList, and Stack to implement the new IMemoryAllocator<TSelf, TOpts> interface, standardizing allocation and free methods. Introduced MemoryPool<T, TOpts> for allocator lifetime management and AllocationHandle access. Updated Program.cs to use MemoryPool, replacing AllocationManager. Minor project file updates included.
This commit is contained in:
74
Misaki.HighPerformance.LowLevel/Buffer/MemoryPool.cs
Normal file
74
Misaki.HighPerformance.LowLevel/Buffer/MemoryPool.cs
Normal file
@@ -0,0 +1,74 @@
|
||||
using Misaki.HighPerformance.LowLevel.Utilities;
|
||||
|
||||
namespace Misaki.HighPerformance.LowLevel.Buffer;
|
||||
|
||||
public unsafe struct MemoryPool<T, TOpts> : IDisposable
|
||||
where T : unmanaged, IMemoryAllocator<T, TOpts>
|
||||
{
|
||||
private T* _pAllocator;
|
||||
private AllocationHandle _allocationHandle;
|
||||
|
||||
public readonly ref T Allocator => ref *_pAllocator;
|
||||
public readonly AllocationHandle AllocationHandle => _allocationHandle;
|
||||
|
||||
public MemoryPool(in TOpts opts)
|
||||
{
|
||||
_pAllocator = (T*)Malloc((nuint)sizeof(T));
|
||||
*_pAllocator = T.Create(opts);
|
||||
|
||||
_allocationHandle = new AllocationHandle
|
||||
{
|
||||
State = _pAllocator,
|
||||
Alloc = &Allocate,
|
||||
Realloc = &Reallocate,
|
||||
Free = &Free,
|
||||
IsValid = null
|
||||
};
|
||||
}
|
||||
|
||||
private static void* Allocate(void* pAllocator, nuint size, nuint alignment, AllocationOption allocationOption, MemoryHandle* pHandle)
|
||||
{
|
||||
return ((T*)pAllocator)->Allocate(size, alignment, allocationOption);
|
||||
}
|
||||
|
||||
private static void* Reallocate(void* pAllocator, void* ptr, nuint oldSize, nuint newSize, nuint alignment, AllocationOption allocationOption, MemoryHandle* pHandle)
|
||||
{
|
||||
if (ptr == null)
|
||||
{
|
||||
return Allocate(pAllocator, newSize, alignment, allocationOption, pHandle);
|
||||
}
|
||||
|
||||
MemoryHandle newHandle;
|
||||
var newPtr = Allocate(pAllocator, newSize, alignment, allocationOption, &newHandle);
|
||||
if (newPtr == null)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
MemCpy(newPtr, ptr, Math.Min(oldSize, newSize));
|
||||
Free(pAllocator, ptr, *pHandle);
|
||||
|
||||
*pHandle = newHandle;
|
||||
return newPtr;
|
||||
}
|
||||
|
||||
private static void Free(void* pAllocator, void* ptr, MemoryHandle handle)
|
||||
{
|
||||
((T*)pAllocator)->Free(ptr);
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
if (_pAllocator == null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_pAllocator->Dispose();
|
||||
|
||||
MemoryUtility.Free(_pAllocator);
|
||||
|
||||
_pAllocator = null;
|
||||
_allocationHandle = default;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user