From 3d02fab4b791b1605fca47f2c7b745abc45edb84 Mon Sep 17 00:00:00 2001 From: Ronald Caesar Date: Wed, 14 Jan 2026 19:45:44 -0400 Subject: [PATCH] memory: add default allocator Signed-off-by: Ronald Caesar --- CMakeLists.txt | 1 + include/bal_memory.h | 10 +++++++ src/bal_memory.c | 65 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 src/bal_memory.c diff --git a/CMakeLists.txt b/CMakeLists.txt index 9038b3c..e1dfad7 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -37,6 +37,7 @@ add_library(Ballistic STATIC src/decoder_table_gen.c src/bal_engine.c src/bal_translator.c + src/bal_memory.c ) target_include_directories(Ballistic PUBLIC include) diff --git a/include/bal_memory.h b/include/bal_memory.h index bfcf18b..d51c831 100644 --- a/include/bal_memory.h +++ b/include/bal_memory.h @@ -10,6 +10,7 @@ #ifndef BALLISTIC_MEMORY_H #define BALLISTIC_MEMORY_H +#include "bal_attributes.h" #include #include @@ -57,6 +58,15 @@ typedef struct } bal_allocator_t; +/*! + * @brief Populates an allocator struct with the default implementation. + * + * @param[out] allocator The strict to populate. Must not be NULL. + * + * @warn Only supports Windows and POSIX systems. + */ +BAL_COLD void get_default_allocator(bal_allocator_t *out_allocator); + #endif /* BALLISTIC_MEMORY_H */ /*** end of file ***/ diff --git a/src/bal_memory.c b/src/bal_memory.c new file mode 100644 index 0000000..9f02604 --- /dev/null +++ b/src/bal_memory.c @@ -0,0 +1,65 @@ +#include "bal_memory.h" +#include "bal_platform.h" +#include +#include + +void *default_allocate(void *, size_t, size_t); +void default_free(void *, void *, size_t); + +void +get_default_allocator (bal_allocator_t *out_allocator) +{ + out_allocator->allocator = NULL; + out_allocator->allocate = default_allocate; + out_allocator->free = default_free; +} + +#if BAL_PLATFORM_POSIX + +void * +default_allocate (void *allocator, size_t alignment, size_t size) +{ + if (0 == size) + { + return NULL; + } + + void *memory = aligned_alloc(alignment, size); + + return memory; +} + +void +default_free (void *allocator, void *pointer, size_t size) +{ + free(pointer); +} + +#endif /* BAL_PLATFORM_POSIX */ + +#if BAL_PLATFORM_WINDOWS + +#include + +void * +default_allocate (void *allocator, size_t alignment, size_t size) +{ + if (0 == size) + { + return NULL; + } + + void *memory = _aligned_malloc(alignment, size); + + return memory; +} + +void +default_free (void *allocator, void *pointer, size_t size) +{ + _aligned_free(pointer); +} + +#endif /* BAL_PLATFORM_WINDOWS */ + +/*** end of file ***/