Skip to content

Instantly share code, notes, and snippets.

@Jayatubi
Created October 18, 2019 07:47
Show Gist options
  • Save Jayatubi/5c870623eb1ded004e76c2a3085f3141 to your computer and use it in GitHub Desktop.
Save Jayatubi/5c870623eb1ded004e76c2a3085f3141 to your computer and use it in GitHub Desktop.
#include "MemoryPool.h"
namespace GX
{
#define GX_ENABLE_MEMORY_POOL
U8* MemoryPoolAllocator::allocImpl(U32 size)
{
U8* result = nullptr;
#ifdef GX_ENABLE_MEMORY_POOL
#define MEM_POOL_ALLOC_IMPL(Power) if (result == nullptr && size <= 1 << Power) result = MemoryPool<(1 << Power)>::shared_pool().acquire();
MEM_POOL_ALLOC_IMPL(0);
MEM_POOL_ALLOC_IMPL(1);
MEM_POOL_ALLOC_IMPL(2);
MEM_POOL_ALLOC_IMPL(3);
MEM_POOL_ALLOC_IMPL(4);
MEM_POOL_ALLOC_IMPL(5);
MEM_POOL_ALLOC_IMPL(6);
MEM_POOL_ALLOC_IMPL(7);
MEM_POOL_ALLOC_IMPL(8);
MEM_POOL_ALLOC_IMPL(9);
MEM_POOL_ALLOC_IMPL(10);
#undef MEM_POOL_ALLOC_IMPL
#endif
if (result == nullptr) result = (U8*)::malloc(size);
return result;
}
void MemoryPoolAllocator::freeImpl(U8* pData, U32 assumeSize)
{
bool released = false;
#ifdef GX_ENABLE_MEMORY_POOL
#define MEM_POOL_FREE_IMPL(Power) if (!released && assumeSize <= (1 << Power)) released = MemoryPool<(1 << Power)>::shared_pool().release(pData);
MEM_POOL_FREE_IMPL(0);
MEM_POOL_FREE_IMPL(1);
MEM_POOL_FREE_IMPL(2);
MEM_POOL_FREE_IMPL(3);
MEM_POOL_FREE_IMPL(4);
MEM_POOL_FREE_IMPL(5);
MEM_POOL_FREE_IMPL(6);
MEM_POOL_FREE_IMPL(7);
MEM_POOL_FREE_IMPL(8);
MEM_POOL_FREE_IMPL(9);
MEM_POOL_FREE_IMPL(10);
#undef MEM_POOL_FREE_IMPL
#endif
if (!released) ::free(pData);
}
#ifdef GX_ENABLE_MEMORYPOOL_STATS
void MemoryPoolAllocator::dumpStats()
{
#ifdef GX_ENABLE_MEMORY_POOL
#define MEM_POOL_DUMP(Power) MemoryPool<(1 << Power)>::shared_pool().dumpStats()
MEM_POOL_DUMP(0);
MEM_POOL_DUMP(1);
MEM_POOL_DUMP(2);
MEM_POOL_DUMP(3);
MEM_POOL_DUMP(4);
MEM_POOL_DUMP(5);
MEM_POOL_DUMP(6);
MEM_POOL_DUMP(7);
MEM_POOL_DUMP(8);
MEM_POOL_DUMP(9);
MEM_POOL_DUMP(10);
#undef MEM_POOL_DUMP
#endif
}
#endif
}
void* cc_malloc(unsigned size)
{
return GX::MemoryPoolAllocator::allocImpl(size);
}
void cc_free(void* pointer, unsigned size)
{
if (pointer != nullptr)
{
GX::MemoryPoolAllocator::freeImpl((GX::U8*)pointer, size);
}
}
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS && TARGET_IPHONE_SIMULATOR == 0) || CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID
//# define GX_OVERLOAD_NEW
#endif
#if defined(GX_OVERLOAD_NEW)
#if defined(ENABLE_MEMORY_TRACK)
# define MEMORY_TRACK_ARG nullptr, nullptr, 0,
#else
# define MEMORY_TRACK_ARG
#endif
void* operator new(size_t size)
{
return CC_Alloc(MEMORY_TRACK_ARG size);
}
void* operator new[](size_t size)
{
return CC_Alloc(MEMORY_TRACK_ARG size);
}
void operator delete(void* ptr) _NOEXCEPT
{
CC_Free(ptr);
}
void operator delete[](void* ptr) _NOEXCEPT
{
CC_Free(ptr);
}
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment