Files
Misaki.HighPerformance/Misaki.HighPerformance.LowLevel/Buffer/MemoryPool.cs
Misaki aae8e2826f feat(core)!: refactor safety/debug defines, remove FreeList in JobSchedular
Refactor to use MHP_ENABLE_SAFETY_CHECKS, MHP_ENABLE_STACKTRACE, and MHP_ENABLE_MIMALLOC for feature toggling. Remove FreeList allocator in JobSchedular and debug-layer code, simplifying memory management. Improve memory leak detection and reporting, update memory allocation API, and guard all safety/debug features with new defines. Update csproj files, README, and code samples to match new API and toggles. Fix and improve collection types for correct behavior with and without safety checks. The codebase is now more modular and easier to configure for different build environments.

BREAKING CHANGE: Old defines (ENABLE_SAFETY_CHECKS, ENABLE_DEBUG_LAYER, ENABLE_MIMALLOC) are replaced with MHP_* equivalents. FreeList allocator and related debug features are removed. Some APIs and behaviors have changed for safety/debug configuration.
2026-03-30 15:21:09 +09:00

96 lines
2.3 KiB
C#

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
#if MHP_ENABLE_SAFETY_CHECKS
, MemoryHandle* pHandle
#endif
)
{
return ((T*)pAllocator)->Allocate(size, alignment, allocationOption);
}
private static void* Reallocate(void* pAllocator, void* ptr, nuint oldSize, nuint newSize, nuint alignment, AllocationOption allocationOption
#if MHP_ENABLE_SAFETY_CHECKS
, MemoryHandle* pHandle
#endif
)
{
if (ptr == null)
{
return Allocate(pAllocator, newSize, alignment, allocationOption
#if MHP_ENABLE_SAFETY_CHECKS
, pHandle
#endif
);
}
var newPtr = Allocate(pAllocator, newSize, alignment, allocationOption
#if MHP_ENABLE_SAFETY_CHECKS
, pHandle
#endif
);
if (newPtr == null)
{
return null;
}
MemCpy(newPtr, ptr, Math.Min(oldSize, newSize));
Free(pAllocator, ptr
#if MHP_ENABLE_SAFETY_CHECKS
, *pHandle
#endif
);
return newPtr;
}
private static void Free(void* pAllocator, void* ptr
#if MHP_ENABLE_SAFETY_CHECKS
, MemoryHandle handle
#endif
)
{
((T*)pAllocator)->Free(ptr);
}
public void Dispose()
{
if (_pAllocator == null)
{
return;
}
_pAllocator->Dispose();
MemoryUtility.Free(_pAllocator);
_pAllocator = null;
_allocationHandle = default;
}
}