pound-emu_pound/core/memory/arena.cpp
Ronald Caesar d3c97317ef filesystem: Add memory arena allocator
I wanted a fast and predictable memory allocator before I start working on the virtual filesystem.
Functions like malloc and realloc will not be used anymore, instead, the allocator will
need to be passed as a function parameter when doing any kind of heap allocation. For example

    char* create_string(Memory::Arena *allocator);
    int* create_int_array(Memory::Arena *allocator, int size);

The definition MEMORY_CAPACITY in arena.h sets the amount of memory the arena can use.
The number can be increased as needed.

Signed-off-by: Ronald Caesar <github43132@proton.me>
2025-07-07 11:37:55 -04:00

33 lines
1 KiB
C++

#include "arena.h"
#include "Base/Assert.h"
Memory::Arena Memory::arena_init() {
// TODO(GloriousTaco): The line below is stupidly unsafe. Replace malloc with mmap() and check the return value.
auto data =
static_cast<uint8_t*>(malloc(sizeof(uint8_t) * MEMORY_CAPACITY));
Memory::Arena arena = {
.capacity = MEMORY_CAPACITY,
.size = 0,
.data = data,
};
return arena;
}
const uint8_t* Memory::arena_allocate(Memory::Arena* arena,
const std::size_t size) {
ASSERT(arena != nullptr);
ASSERT(arena->size + size < arena->capacity);
const uint8_t* const data = &(arena->data[arena->size]);
arena->size += size;
return data;
}
void Memory::arena_reset(Memory::Arena* arena) {
ASSERT(arena != nullptr);
arena->size = 0;
}
void Memory::arena_free(Memory::Arena* arena) {
ASSERT(arena != nullptr);
arena->capacity = 0;
arena->size = 0;
// TODO(GloriousTaco): Replace free with a memory safe alternative.
free(arena->data);
}