memory/allocator: add ALLOC_VIA macros

This commit is contained in:
Andrei Alexeyev 2023-02-09 15:20:01 +01:00
parent e555126854
commit 9089a2f16e
No known key found for this signature in database
GPG key ID: 72D26128040B9690
2 changed files with 43 additions and 0 deletions

View file

@ -48,6 +48,10 @@ void *allocator_alloc_aligned(Allocator *alloc, size_t size, size_t alignment) {
return alloc->procs.alloc_aligned(alloc, size, alignment);
}
void *allocator_alloc_array_aligned(Allocator *alloc, size_t num_members, size_t size, size_t alignment) {
return allocator_alloc_aligned(alloc, mem_util_calc_array_size(num_members, size), alignment);
}
void allocator_free(Allocator *alloc, void *mem) {
return NOT_NULL(alloc->procs.free)(alloc, mem);
}

View file

@ -49,6 +49,13 @@ void *allocator_alloc_aligned(Allocator *alloc, size_t size, size_t alignment)
attr_returns_allocated
attr_nonnull_all;
void *allocator_alloc_array_aligned(Allocator *alloc, size_t num_members, size_t size, size_t alignment)
attr_alloc_size(2, 3)
attr_alloc_align(4)
attr_malloc
attr_returns_allocated
attr_nonnull_all;
void allocator_free(Allocator *alloc, void *mem)
attr_nonnull(1);
@ -57,3 +64,35 @@ void allocator_deinit(Allocator *alloc)
void allocator_init_from_arena(Allocator *alloc, MemArena *arena)
attr_nonnull_all;
/*
* These are similar to the macros in memory.h, except they also take an Allocator pointer as the
* first argument.
*/
#define ALLOC_VIA(_allocator, _type, ...)\
MACROHAX_OVERLOAD_HASARGS(ALLOC_VIA_, __VA_ARGS__)(_allocator, _type, ##__VA_ARGS__)
#define ALLOC_VIA_0(_allocator, _type) \
(_type *)__builtin_choose_expr( \
alignof(_type) > alignof(max_align_t), \
allocator_alloc_aligned(_allocator, sizeof(_type), alignof(_type)), \
allocator_alloc(_allocator, sizeof(_type)))
#define ALLOC_VIA_1(_allocator, _type, ...) ({ \
auto _alloc_ptr = ALLOC_VIA_0(_allocator, _type); \
*_alloc_ptr = (_type) __VA_ARGS__; \
_alloc_ptr; \
})
#define ALLOC_ARRAY_VIA(_allocator, _nmemb, _type) \
(_type *)__builtin_choose_expr( \
alignof(_type) > alignof(max_align_t), \
allocator_alloc_array_aligned(_allocator, _nmemb, sizeof(_type), alignof(_type)), \
allocator_alloc_array(_allocator, _nmemb, sizeof(_type)))
#define ALLOC_FLEX_VIA(_allocator, _type, _extra_size) \
(_type *)__builtin_choose_expr( \
alignof(_type) > alignof(max_align_t), \
allocator_alloc_aligned(_allocator, sizeof(_type) + (_extra_size), alignof(_type)), \
allocator_alloc(_allocator, sizeof(_type) + (_extra_size)))