Add function to create array from preallocated buffer
This commit is contained in:
@@ -227,21 +227,38 @@ GenericArray _array_alloc_capacity(const Allocator *allocator, u64 capacity, Arr
|
||||
GenericArray output = NULL;
|
||||
|
||||
u64 allocation_size = _array_calc_alloc_size(capacity, item_size);
|
||||
ArrayHeader *header = wapp_mem_allocator_alloc(allocator, allocation_size);
|
||||
if (!header) {
|
||||
void *buffer = wapp_mem_allocator_alloc(allocator, allocation_size);
|
||||
if (!buffer) {
|
||||
goto RETURN_ARRAY_ALLOC;
|
||||
}
|
||||
|
||||
output = (u8 *)(header + 1);
|
||||
header->magic = WAPP_ARRAY_MAGIC;
|
||||
header->count = flags & ARRAY_INIT_FILLED ? capacity : 0;
|
||||
header->capacity = capacity;
|
||||
header->item_size = item_size;
|
||||
output = _array_from_preallocated_buffer(buffer, allocation_size, flags, item_size);
|
||||
|
||||
RETURN_ARRAY_ALLOC:
|
||||
return output;
|
||||
}
|
||||
|
||||
|
||||
GenericArray _array_from_preallocated_buffer(void *buffer, u64 buffer_size, ArrayInitFlags flags,
|
||||
u64 item_size) {
|
||||
wapp_runtime_assert(buffer != NULL, "`buffer` should not be NULL");
|
||||
|
||||
i64 data_buffer_size = (i64)buffer_size - (i64)(sizeof(ArrayHeader));
|
||||
if (data_buffer_size <= 0) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
u64 item_capacity = (u64)data_buffer_size / item_size;
|
||||
ArrayHeader *header = (ArrayHeader *)buffer;
|
||||
GenericArray output = (u8 *)(header + 1);
|
||||
header->magic = WAPP_ARRAY_MAGIC;
|
||||
header->count = flags & ARRAY_INIT_FILLED ? item_capacity : 0;
|
||||
header->capacity = item_capacity;
|
||||
header->item_size = item_size;
|
||||
|
||||
return output;
|
||||
}
|
||||
|
||||
wapp_persist inline void _array_validate(const GenericArray array, u64 item_size) {
|
||||
ArrayHeader *header = _array_header(array);
|
||||
wapp_runtime_assert(WAPP_ARRAY_MAGIC == header->magic, "`array` is not a valid wapp array");
|
||||
|
||||
@@ -174,6 +174,8 @@ typedef enum {
|
||||
#define wapp_array_calc_alloc_size(TYPE, CAPACITY) _array_calc_alloc_size(CAPACITY, sizeof(TYPE))
|
||||
#define wapp_array_alloc_capacity(TYPE, ALLOCATOR_PTR, CAPACITY, FLAGS) \
|
||||
((TYPE *)_array_alloc_capacity(ALLOCATOR_PTR, CAPACITY, FLAGS, sizeof(TYPE)))
|
||||
#define wapp_array_from_preallcated_buffer(TYPE, BUFFER, BUFFER_SIZE) \
|
||||
((TYPE *)_array_from_preallcated_buffer(BUFFER, BUFFER_SIZE, sizeof(TYPE)))
|
||||
|
||||
|
||||
typedef struct header ArrayHeader;
|
||||
|
||||
Reference in New Issue
Block a user