#pragma once #ifndef ULE_ALLOC_H #define ULE_ALLOC_H #include "config.h" #include "types.h" // define a consistent memory allocation interface // trailing void* is a pointer to some allocator state, if relevant. // will be unused for malloc/calloc/realloc/free, as the allocator state is internal to the OS. // overloads should exist which do nothing with the trailing paramter. typedef void* (*mallocator) (size_t, void*); typedef void* (*callocator) (size_t, size_t, void*); typedef void* (*reallocator) (void*, size_t, void*); typedef void (*freeer) (void*, void*); typedef void (*clearer) ( void*); typedef void (*destroyer) ( void*); // operating system allocator wrappers extern void* pMalloc(size_t size); extern void* pMalloc(size_t size, void* allocatorState); extern void* pCalloc(size_t maxNumOfElements, size_t elementSize); extern void* pCalloc(size_t maxNumOfElements, size_t elementSize, void* allocatorState); extern void* pRealloc(void* buffer, size_t newSize); extern void* pRealloc(void* buffer, size_t newSize, void* allocatorState); extern void pFree(void* ptr); extern void pFree(void* ptr, void* allocatorState); extern void pFree(const void* ptr); extern void pFree(const void* ptr, void* allocatorState); struct Allocator { void* state; mallocator mallocate; callocator callocate; reallocator reallocate; freeer free; // releases a specific piece of memory clearer clear; // should release all the memory owned by this allocator at once. destroyer destroy; // releases all the memory owned by this allocator, and also destroys the allocator. static Allocator* GetDefault(); Allocator() { this->state = null; this->mallocate = pMalloc; this->callocate = pCalloc; this->reallocate = pRealloc; this->free = pFree; this->clear = null; this->destroy = null; } Allocator(mallocator mallocate, freeer free) { this->state = null; this->mallocate = mallocate; this->callocate = null; this->reallocate = null; this->free = free; this->clear = null; this->destroy = null; } }; struct Arena { u32 bufferSizeInBytes; u32 index; u8* buffer; static Arena* Init(u32 sizeInBytes = 1024); void* Alloc(u32 sizeInBytes); void Clear(); }; #endif