diff options
Diffstat (limited to 'src/bootstrap/darray.h')
-rw-r--r-- | src/bootstrap/darray.h | 23 |
1 files changed, 23 insertions, 0 deletions
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 { | |||
25 | // Return the last element of the array. Can be used to build stacks. | 25 | // Return the last element of the array. Can be used to build stacks. |
26 | #define array_pop(ARR) (ARR)[--array_head(ARR)->size] | 26 | #define array_pop(ARR) (ARR)[--array_head(ARR)->size] |
27 | 27 | ||
28 | // Insert N bytes from the SRC array into the ARR dynamic array. | ||
29 | #define array_insert(ARR, SRC, N) \ | ||
30 | ((ARR) = _array_insert(ARR, SRC, N, sizeof(*(ARR)))) | ||
31 | |||
28 | // Free the memory from the original allocated position. | 32 | // Free the memory from the original allocated position. |
29 | #define array_free(ARR) ((ARR) ? free(array_head(ARR)), (ARR) = NULL : 0) | 33 | #define array_free(ARR) ((ARR) ? free(array_head(ARR)), (ARR) = NULL : 0) |
30 | 34 | ||
@@ -52,4 +56,23 @@ _array_maybe_grow(void *arr, size_t type_size) { | |||
52 | return arr; | 56 | return arr; |
53 | } | 57 | } |
54 | 58 | ||
59 | static inline | ||
60 | char * _array_insert(char *arr, const char *src, size_t n_bytes, size_t type_size) { | ||
61 | ArrayHeader *head = array_head(arr); | ||
62 | size_t new_size = n_bytes + head->size; | ||
63 | if (new_size >= head->cap * type_size) { | ||
64 | if (head->cap == 0) { | ||
65 | head->cap = 1; | ||
66 | } | ||
67 | while (new_size >= head->cap * type_size) { | ||
68 | head->cap *= 2; | ||
69 | } | ||
70 | head = realloc(head, head->cap * type_size + sizeof(ArrayHeader)); | ||
71 | } | ||
72 | arr = (char *)head + sizeof(ArrayHeader); | ||
73 | memcpy((arr + head->size), src, n_bytes); | ||
74 | head->size = new_size; | ||
75 | return arr; | ||
76 | } | ||
77 | |||
55 | #endif // BDL_DARRAY_H | 78 | #endif // BDL_DARRAY_H |