diff options
| author | iamcheeseman <[email protected]> | 2026-04-06 17:04:05 -0400 |
|---|---|---|
| committer | iamcheeseman <[email protected]> | 2026-04-06 17:06:53 -0400 |
| commit | 957c64c7b8b5e98d8a03dd84c7e27e7991fb9dbc (patch) | |
| tree | f5fc230703791cee8d8e7851fb87eaef07ae63a2 /common/dyn_arr.c | |
Initial commit
Diffstat (limited to 'common/dyn_arr.c')
| -rw-r--r-- | common/dyn_arr.c | 44 |
1 files changed, 44 insertions, 0 deletions
diff --git a/common/dyn_arr.c b/common/dyn_arr.c new file mode 100644 index 0000000..f378702 --- /dev/null +++ b/common/dyn_arr.c @@ -0,0 +1,44 @@ +#include "dyn_arr.h" + +#include <stdio.h> +#include <assert.h> + +void *_da_create(size_t type_size, int init_cap) +{ + init_cap = init_cap < DA_MIN_CAP + ? DA_MIN_CAP + : init_cap; + + int *arr = (int*)mem_alloc(type_size * init_cap + sizeof(int) * 2); + + arr[0] = 0; + arr[1] = init_cap; + return (void*)(arr + 2); +} + +void *_da_append_slot(size_t type_size, void **arr) +{ + int *cap = da_cap_ptr(*arr); + int *len = da_len_ptr(*arr); + + (*len)++; + + if (*len > *cap) { + *cap *= DA_GROW_RATE; + + void* base = da_base(*arr); + base = mem_realloc(base, (type_size * *cap) + sizeof(int) * 2); + assert(base != NULL); // Just to handle the case + *arr = (void*)((int*)base + 2); + + len = da_len_ptr(*arr); + } + + return (char*)*arr + ((*len - 1) * type_size); +} + +void da_free(void *arr) +{ + void *base = da_base(arr); + mem_free(base); +} |
