From 008f173f9b9e52ae41683939614239059c0d3b04 Mon Sep 17 00:00:00 2001 From: Bad Diode Date: Tue, 19 Oct 2021 18:21:25 +0200 Subject: Change string/symbol representation to use darray.h --- src/bootstrap/darray.h | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) (limited to 'src/bootstrap/darray.h') diff --git a/src/bootstrap/darray.h b/src/bootstrap/darray.h index bb49cdd..db6234d 100644 --- a/src/bootstrap/darray.h +++ b/src/bootstrap/darray.h @@ -25,6 +25,10 @@ typedef struct ArrayHeader { // Return the last element of the array. Can be used to build stacks. #define array_pop(ARR) (ARR)[--array_head(ARR)->size] +// Insert N bytes from the SRC array into the ARR dynamic array. +#define array_insert(ARR, SRC, N) \ + ((ARR) = _array_insert(ARR, SRC, N, sizeof(*(ARR)))) + // Free the memory from the original allocated position. #define array_free(ARR) ((ARR) ? free(array_head(ARR)), (ARR) = NULL : 0) @@ -52,4 +56,23 @@ _array_maybe_grow(void *arr, size_t type_size) { return arr; } +static inline +char * _array_insert(char *arr, const char *src, size_t n_bytes, size_t type_size) { + ArrayHeader *head = array_head(arr); + size_t new_size = n_bytes + head->size; + if (new_size >= head->cap * type_size) { + if (head->cap == 0) { + head->cap = 1; + } + while (new_size >= head->cap * type_size) { + head->cap *= 2; + } + head = realloc(head, head->cap * type_size + sizeof(ArrayHeader)); + } + arr = (char *)head + sizeof(ArrayHeader); + memcpy((arr + head->size), src, n_bytes); + head->size = new_size; + return arr; +} + #endif // BDL_DARRAY_H -- cgit v1.2.1