summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorSøren Sandmann Pedersen <sandmann@daimi.au.dk>2009-04-16 20:23:08 -0400
committerSøren Sandmann Pedersen <sandmann@daimi.au.dk>2009-04-16 20:23:08 -0400
commit35c9b3794618121cbc189e93e79daf1a5594fc42 (patch)
tree463163c952283184d327ecb5f3a2a41daaa66b45
parenta1c56112aee2597873e56f4715822fef820a86f6 (diff)
Add generic arrays
-rw-r--r--array.c66
-rw-r--r--libnul.h8
2 files changed, 60 insertions, 14 deletions
diff --git a/array.c b/array.c
index c6ea712..945c4d4 100644
--- a/array.c
+++ b/array.c
@@ -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 **
diff --git a/libnul.h b/libnul.h
index 5cef6d1..24e40a4 100644
--- a/libnul.h
+++ b/libnul.h
@@ -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);