From 6ad18ea8a3966e10b3d73b56663c502ef35e6f09 Mon Sep 17 00:00:00 2001 From: talha aamir Date: Wed, 24 Sep 2025 21:27:03 +0500 Subject: Added files to git. - Starting index buffer chapter of vulkan-tutorial --- arena.h | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100755 arena.h (limited to 'arena.h') diff --git a/arena.h b/arena.h new file mode 100755 index 0000000..c7340a0 --- /dev/null +++ b/arena.h @@ -0,0 +1,110 @@ +#pragma once + +#include + +#ifdef ARENA_TYPES +#include +#include +typedef uint8_t b8; +#endif + +#ifndef ALIGNMENT +#define ALIGNMENT (2*sizeof(void*)) +#endif + +struct Arena { + unsigned char* buffer; + size_t prev_offset; + size_t curr_offset; + size_t capacity; +}; +typedef struct Arena Arena; + +struct TempArena { + Arena *a; + size_t saved_prev_offset; + size_t saved_curr_offset; +}; +typedef struct TempArena TempArena; + +// definition +b8 is_power_of_two(uintptr_t x); +uintptr_t fast_modulo(uintptr_t p, uintptr_t a); +uintptr_t align_forward(uintptr_t ptr, uintptr_t alignment); +void arena_init(Arena* a, unsigned char *memory, size_t capacity); +void* arena_alloc(Arena* a, size_t size); +void arena_clear(Arena* a); + +TempArena temp_arena_start(Arena *a); +void temp_arena_end(Arena* a); + +// implementation +b8 is_power_of_two(uintptr_t x) { + return (x & (x-1)) == 0; +} + +uintptr_t fast_modulo(uintptr_t p, uintptr_t a) { + return (p & (a - 1)); +} + +uintptr_t align_forward(uintptr_t ptr, size_t alignment) { + uintptr_t p, a, modulo; + + assert(is_power_of_two(alignment)); + + p = ptr; + a = (uintptr_t)alignment; + modulo = fast_modulo(p, a); + + if (modulo != 0) { + p += (a - modulo); + } + + return p; +} + +void arena_init(Arena* a, unsigned char *memory, size_t capacity) { + a->buffer = memory; + a->prev_offset = 0; + a->curr_offset = 0; + a->capacity = capacity; +} + +void* arena_alloc(Arena* a, size_t size) { + void *ptr = NULL; + + assert(is_power_of_two(ALIGNMENT)); + + uintptr_t curr_ptr = (uintptr_t)a->buffer + a->curr_offset; + uintptr_t offset = align_forward(curr_ptr, ALIGNMENT); + offset = offset - (uintptr_t)a->buffer; + size_t next_offset = offset + size; + + assert(next_offset <= a->capacity); + + ptr = &a->buffer[offset]; + a->prev_offset = a->curr_offset; + a->curr_offset = next_offset; + memset(ptr, 0, size); + + return ptr; +} + +void arena_clear(Arena* a) { + a->curr_offset = 0; + a->prev_offset = 0; +} + +TempArena temp_arena_start(Arena* main) { + TempArena tmp = {}; + tmp.a = main; + tmp.saved_prev_offset = main->prev_offset; + tmp.saved_curr_offset = main->curr_offset; + + return tmp; +} + +void temp_arena_end(TempArena tmp) { + tmp.a->prev_offset = tmp.saved_prev_offset; + tmp.a->curr_offset = tmp.saved_curr_offset; +} -- cgit v1.2.3