From 8e41b627bc04f2f4d0c9a8eeb15142748293db4f Mon Sep 17 00:00:00 2001 From: Abdelrahman Said Date: Sat, 24 Jan 2026 20:45:52 +0000 Subject: [PATCH] Add function to create array from preallocated buffer --- src/base/array/array.c | 31 ++++++++++++++++++++++++------- src/base/array/array.h | 2 ++ 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/src/base/array/array.c b/src/base/array/array.c index 147b29a..e47c125 100644 --- a/src/base/array/array.c +++ b/src/base/array/array.c @@ -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"); diff --git a/src/base/array/array.h b/src/base/array/array.h index 7f06326..f996a23 100644 --- a/src/base/array/array.h +++ b/src/base/array/array.h @@ -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;