From 2f246bdf592d91c643bdc8c9c138f995c67f6ae7 Mon Sep 17 00:00:00 2001 From: rhuibertsjr Date: Fri, 26 Apr 2024 17:00:32 +0200 Subject: [PATCH] Added: growable arenas on allocation --- src/arena.c | 40 +++++++++++++++++++++++++++++++++++++++- src/arena.h | 2 +- src/base.h | 4 ++++ src/main.c | 4 ++++ 4 files changed, 48 insertions(+), 2 deletions(-) diff --git a/src/arena.c b/src/arena.c index 3f910ea..b313863 100644 --- a/src/arena.c +++ b/src/arena.c @@ -10,10 +10,11 @@ arena_initialize(u64 size, b8 growable) result = (Arena*) backing_buffer; result->backing_buffer = backing_buffer; + result->current = result; // rhjr: immutable arena header result->base_pos = sizeof(Arena); - result->commit_pos = sizeof(Arena); + result->offset = sizeof(Arena); result->growable = growable; result->size = size; @@ -35,6 +36,43 @@ arena_initialize_default() internal void * arena_allocate(Arena *arena, u64 size) { + Arena *current = arena->current; + u64 pos_mem = current->offset; + u64 pos_new = current->offset + size; + + if (current->size < pos_new && current->growable) + { + Arena *new_memory_bock; + + if (size > ARENA_DEFAULT_RESERVE_SIZE) + { + // rhjr: TODO add support for allocations larger then a single page, in a + // single allocation call. + } + else + { + new_memory_bock = arena_initialize_default(); + + if (new_memory_bock) + { + sll_stack_push(arena->current, new_memory_bock, prev); + + current = new_memory_bock; + pos_mem = current->offset; + pos_new = current->offset + size; + } + + } + + } + + void *memory = (void*)((u64) current->backing_buffer + pos_mem); + arena->offset = pos_new; + + platform_memory_commit(memory, size); + memset(memory, 0, size); + + return memory; } internal void diff --git a/src/arena.h b/src/arena.h index 103a367..547b837 100644 --- a/src/arena.h +++ b/src/arena.h @@ -13,7 +13,7 @@ struct Arena { struct Arena *prev; u64 *backing_buffer; u64 base_pos; - u64 commit_pos; + u64 offset; u64 size; b8 growable; }; diff --git a/src/base.h b/src/base.h index e7d93f9..db6336e 100644 --- a/src/base.h +++ b/src/base.h @@ -33,6 +33,10 @@ typedef uint8_t b64; #define ASSERT(c) STATEMENT( if (!(c)){ (*(volatile int*)0 = 0); } ) #define STATIC_ASSERT(c,l) typedef u8 Glue(l,__LINE__) [(c)?1:-1] +//= rhjr: linkedlist helpers + +#define sll_stack_push(f,n,next) ((n)->next=(f), (f)=(n)) + //= rhjr: memory helpers #define memory_zero(s,z) memset((s), 0, (z)) diff --git a/src/main.c b/src/main.c index 0d8fb62..b54f935 100644 --- a/src/main.c +++ b/src/main.c @@ -9,5 +9,9 @@ int main(void) { Arena *arena = arena_initialize_default(); + u64* ptr1 = arena_allocate(arena, KB(3)); + u64* ptr2 = arena_allocate(arena, KB(2)); + + arena_release(arena); return 0; }