66 lines
1.6 KiB
C++
66 lines
1.6 KiB
C++
#include "GlobalMemory.h"
|
|
|
|
#include <SDL3/SDL_log.h>
|
|
|
|
void GlobalMemory::init(size_t const size)
|
|
{
|
|
memory = new Byte[size];
|
|
capacity = size;
|
|
available = size;
|
|
}
|
|
|
|
void GlobalMemory::destroy()
|
|
{
|
|
Byte const* originalMemory = memory - (capacity - available);
|
|
delete[] originalMemory;
|
|
memory = nullptr;
|
|
available = 0;
|
|
capacity = 0;
|
|
}
|
|
|
|
Byte* GlobalMemory::allocate(size_t const size)
|
|
{
|
|
assert(size <= available && "No enough space available");
|
|
|
|
Byte* retVal = memory;
|
|
memory += size;
|
|
available -= size;
|
|
SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "ALLOC: %p -> %p (%llu) (avail: %llu)", reinterpret_cast<void*>(retVal), reinterpret_cast<void*>(memory), size, available);
|
|
|
|
return retVal;
|
|
}
|
|
|
|
Byte* GlobalMemory::allocate(size_t const size, size_t const alignment)
|
|
{
|
|
uintptr_t const addr = reinterpret_cast<uintptr_t>(memory);
|
|
uintptr_t const foundOffset = addr % alignment;
|
|
|
|
if (foundOffset == 0)
|
|
{
|
|
return allocate(size);
|
|
}
|
|
|
|
uintptr_t const offset = alignment - foundOffset;
|
|
size_t const allocationSize = size + offset;
|
|
|
|
return offset + allocate(allocationSize);
|
|
}
|
|
|
|
GlobalMemory::State GlobalMemory::getState() const
|
|
{
|
|
SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "TEMP: %p %llu", reinterpret_cast<void*>(memory), available);
|
|
return {
|
|
.memory = memory,
|
|
.available = available,
|
|
};
|
|
}
|
|
|
|
void GlobalMemory::restoreState(State const& state)
|
|
{
|
|
assert(memory >= state.memory); //< Behind top of allocator
|
|
assert(memory - (capacity - available) <= state.memory); //< Ahead of start of allocator
|
|
SDL_LogInfo(SDL_LOG_CATEGORY_SYSTEM, "RESTORE: %p %llu", reinterpret_cast<void*>(memory), available);
|
|
memory = state.memory;
|
|
available = state.available;
|
|
}
|