From 4502339527c6cc49c61035782a5560ce120d6794 Mon Sep 17 00:00:00 2001 From: Jason Hilder Date: Sat, 8 Feb 2025 08:03:27 +0200 Subject: [PATCH] Getting allocators and types under control. --- jh.h | 8 +++---- jh_mem.h | 70 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 74 insertions(+), 4 deletions(-) diff --git a/jh.h b/jh.h index c22c3a3..b9afaa2 100644 --- a/jh.h +++ b/jh.h @@ -19,21 +19,21 @@ To use this library, do this in *one* C: #ifndef JH_INCLUDED #define JH_INCLUDED +#include + +typedef uint8_t byte; typedef uint8_t u8; typedef uint16_t u16; typedef uint32_t u32; typedef uint64_t u64; typedef char i8; -typedef int16_t i32; +typedef int16_t i16; typedef int32_t i32; typedef float f32; typedef double f64; -typedef char byte; -typedef char16_t c16; typedef uintptr_t uptr; -typedef ptrdiff_t size; typedef size_t usize; void jh_sort_int_array(int* array, size_t arrlen, const char* order); diff --git a/jh_mem.h b/jh_mem.h index a5347b5..726eddd 100644 --- a/jh_mem.h +++ b/jh_mem.h @@ -15,9 +15,79 @@ A implementation of the above with changes were I felt I needed them. To use this library, do this in *one* C: #define JH_MEM_IMPLEMENTATION #include "jh_io.h" + +NOTE: +This is intended to be used with the jh.h header. +And will require jh.h as it uses the typedefs defined in that file. + */ #ifndef JH_MEM_INCLUDED #define JH_MEM_INCLUDED +#ifndef DEFAULT_ALIGNMENT +#define DEFAULT_ALIGNMENT (2*sizeof(void *)) +#endif + +typedef struct Arena Arena; +struct Arena { + u8 *data; + usize data_len; + usize prev_offset; + usize curr_offset; +}; + +bool is_power_of_two(uptr x); +uptr align_forward(uptr ptr, usize align); +void *arena_alloc_align(Arena *a, usize size, usize align); +void *arena_alloc(Arena *a, usize size); + +// -------------------------------------- +// -------------------------------------- +// implementation Below +// -------------------------------------- + + +// -------------------------------------- +// Arena Functions Start +// -------------------------------------- + +bool is_power_of_two(uintptr_t x) { + return (x & (x-1)) == 0; +} + +uptr align_forward(uptr ptr, usize align) { + uptr p, a, modulo; + + assert(is_power_of_two(align)); + + p = ptr; + a = (uptr)align; + modulo = p & (a-1); + + if (modulo != 0) { + // If 'p' address is not aligned. + // push the address to the next value which is aligned + p += a - modulo; + } + + return p; +} + +void *arena_alloc_align(Arena *a, usize size, usize align) { + uptr current_ptr = (uptr)a->data + (uptr)a->curr_offset; + uptr offset = align_forward(current_ptr, align); + + // Change to relative offset + offset -= (uptr)a->data; +} + +void *arena_alloc(Arena *a, size_t size) { + return arena_alloc_align(a, size, DEFAULT_ALIGNMENT); +} + +// -------------------------------------- +// Arena Functions END +// -------------------------------------- + #endif