|
|
#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
// the overloads with the 'void*' are to make them conform to the allocator interface above.
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 { mallocator mallocate; callocator callocate; reallocator reallocate; freeer free; // releases a specific piece/chunk of memory, identified by pointer.
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.
void* state;
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; }
Allocator( mallocator mallocate, callocator callocate = null, reallocator reallocate = null, freeer free = null, clearer clear = null, destroyer destroy = null, void* state = null ) { this->mallocate = mallocate; this->callocate = callocate; this->reallocate = reallocate; this->free = free; this->clear = clear; this->destroy = destroy; this->state = state; } };
struct Arena { u32 bufferSizeInBytes; u32 index; u8* buffer;
static Arena* Init(u32 sizeInBytes = 1024);
void* Alloc(u32 sizeInBytes); void Clear(); float PercentUsed(); };
#endif
|