diff options
-rw-r--r-- | array.c | 66 | ||||
-rw-r--r-- | libnul.h | 8 |
2 files changed, 60 insertions, 14 deletions
@@ -138,6 +138,58 @@ array_delete_tail (array_t *array, int n_elements) return array; } +/* Generic arrays + * + * The idiomatic way to use them is like this: + * + * mytype_t *mytypes = nul_array_new (sizeof (mytype_t)); + * mytypes = nul_array_append (mytypes, &a_mytype); + * + * To iterate through, either use nul_array_len() or rely on + * the fact that there will always be at least one element + * with nul bits at the end. + * + */ + +static const int arr_t_magic; + +nul_ptr_t +nul_array_new (int element_size) +{ + return array_new (element_size, &arr_t_magic); +} + +nul_ptr_t +nul_array_append (nul_ptr_t arr, nul_ptr_t element) +{ + array_t *array = get_array (arr, &arr_t_magic); + char *data; + + array = realloc_array (array, array->n_elements + 1); + + data = (char *)array->data; + + data += array->n_elements++ * array->element_size; + memcpy (data, element, array->element_size); + + data += array->element_size; + memset (data, 0, array->element_size); + + return arr; +} + +void +nul_array_free (nul_ptr_t array) +{ + array_free (get_array (array, &arr_t_magic)); +} + +gsize +nul_array_len (nul_ptr_t array) +{ + return get_array (array, &arr_t_magic)->n_elements; +} + /* Pointer arrays. The idiomatic way to iterate through such an array is: * * void **p; @@ -163,20 +215,6 @@ array_delete_tail (array_t *array, int n_elements) * */ -typedef struct parr_t parr_t; - -static const int parr_t_magic; - -struct parr_t -{ - const int *magic; - gssize n_bytes; /* Number of bytes allocated in total */ - gssize n_used; /* Number of pointers in use, not including - * the final NULL pointer - */ - void *data[1]; -}; - static const int parr_t_magic; void ** @@ -50,6 +50,14 @@ typedef void * nul_ptr_t; typedef void * const nul_const_ptr_t; /* + * Generic arrays + */ +nul_ptr_t nul_array_new (int element_size); +nul_ptr_t nul_array_append (nul_ptr_t array, nul_ptr_t element); +gsize nul_array_len (nul_ptr_t array); +void nul_array_free (nul_ptr_t array); + +/* * Pointer arrays */ nul_ptr_t *nul_ptr_array_new (void); |