diff options
| author | Johnny Richard <johnny@johnnyrichard.com> | 2025-04-11 01:15:01 +0200 |
|---|---|---|
| committer | Johnny Richard <johnny@johnnyrichard.com> | 2025-04-14 23:11:22 +0200 |
| commit | e7f69c8fbbbcbddde84933b2becd91e787d1ac63 (patch) | |
| tree | 16cd17da17133494dd06aab614724e76b059d4ad /src/array.c | |
Intial commit
Signed-off-by: Johnny Richard <johnny@johnnyrichard.com>
Diffstat (limited to 'src/array.c')
| -rw-r--r-- | src/array.c | 41 |
1 files changed, 41 insertions, 0 deletions
diff --git a/src/array.c b/src/array.c new file mode 100644 index 0000000..95c2b7b --- /dev/null +++ b/src/array.c @@ -0,0 +1,41 @@ +#include <assert.h> +#include <stdlib.h> +#include <stdint.h> + +#include "array.h" + +void * +array_new(size_t item_size) +{ + array_header_t *h = malloc((item_size * ARRAY_INITIAL_CAPACITY) + sizeof(array_header_t)); + if (h == NULL) { + return NULL; + } + h->length = 0; + h->item_size = item_size; + h->capacity = ARRAY_INITIAL_CAPACITY; + return h + sizeof(array_header_t); +} + +array_header_t * +array_get_header(void *arr) +{ + return (array_header_t *) arr - sizeof(array_header_t); +} + +void * +array_grow(void *arr) +{ + array_header_t *h = array_get_header(arr); + h->capacity *= 2; + h = realloc(h, sizeof(array_header_t) + (h->capacity * h->item_size)); + return h + sizeof(array_header_t); +} + +size_t +array_length(void *arr) +{ + assert(arr); + array_header_t *header = array_get_header(arr); + return header->length; +} |
