diff options
Diffstat (limited to 'src/core/std_allocator.c')
-rw-r--r-- | src/core/std_allocator.c | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/src/core/std_allocator.c b/src/core/std_allocator.c new file mode 100644 index 0000000..ecfa806 --- /dev/null +++ b/src/core/std_allocator.c @@ -0,0 +1,37 @@ +#include "std_allocator.h" + +#include <stdlib.h> + +static void *allocate(size_t size, size_t alignment, void *user_data) { + (void)user_data; + + // `aligned_alloc(3)` requires that the requested size be a multiple of the requested alignment. + // this is safe to do, because we ignore `old_size` everywhere else. + size_t actual_size = (size + alignment - 1) & ~(alignment - 1); + + return aligned_alloc(alignment, actual_size); +} + +static void deallocate(void *old_ptr, size_t old_size, void *user_data) { + (void)old_size; + (void)user_data; + free(old_ptr); +} + +static void *reallocate(void *old_ptr, size_t old_size, size_t new_size, size_t alignment, void *user_data) { + (void)old_size; + (void)alignment; + (void)user_data; + + // fixme: does `realloc(3)` preserve alignment? + return realloc(old_ptr, new_size); +} + +SandAllocator sand_new_std_allocator() { + return (SandAllocator) { + .allocate = allocate, + .deallocate = deallocate, + .reallocate = reallocate, + .user_data = NULL, + }; +} |