diff options
author | Omniscient <17525998+omnisci3nce@users.noreply.github.com> | 2024-02-25 11:02:46 +1100 |
---|---|---|
committer | Omniscient <17525998+omnisci3nce@users.noreply.github.com> | 2024-02-25 11:02:46 +1100 |
commit | 4b9ab2ec5acf2ecf2e96c38733a835b964664171 (patch) | |
tree | 3a20f08c99e9f5036bccf7916cec56fbb7fd0ec0 /src/std/mem.c | |
parent | 1e1facd09ade50ffaf421cffe53ff7ddddab2793 (diff) |
add an arena allocator first impl
Diffstat (limited to 'src/std/mem.c')
-rw-r--r-- | src/std/mem.c | 26 |
1 files changed, 26 insertions, 0 deletions
diff --git a/src/std/mem.c b/src/std/mem.c new file mode 100644 index 0000000..c30f76d --- /dev/null +++ b/src/std/mem.c @@ -0,0 +1,26 @@ +#include "mem.h" +#include <stddef.h> +#include <stdint.h> +#include <string.h> +#include "log.h" + +#ifndef DEFAULT_ALIGNMENT +#define DEFAULT_ALIGNMENT (2 * sizeof(void*)) +#endif + +void* arena_alloc_align(arena* a, size_t size, size_t align) { + ptrdiff_t padding = -(uintptr_t)a->begin & (align - 1); + ptrdiff_t available = a->end - a->begin - padding; + TRACE("Padding %td available %td", padding, available); + if (available < 0 || (ptrdiff_t)size > available) { + ERROR_EXIT("Arena ran out of memory\n"); + } + void* p = a->begin + padding; + a->begin += padding + size; + return memset(p, 0, size); +} +void* arena_alloc(arena* a, size_t size) { return arena_alloc_align(a, size, DEFAULT_ALIGNMENT); } + +arena arena_create(void* backing_buffer, size_t capacity) { + return (arena){ .begin = backing_buffer, .end = backing_buffer + (ptrdiff_t)capacity }; +}
\ No newline at end of file |