changeset 736:ca837a4417f5

Add simple growing pointerlist data stucture implementation.
author Matti Hamalainen <ccr@tnsp.org>
date Wed, 07 Dec 2022 15:03:09 +0200
parents 31bc1ed07cf5
children 6b778871f770
files th_datastruct.c th_datastruct.h
diffstat 2 files changed, 84 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- a/th_datastruct.c	Wed Dec 07 12:14:39 2022 +0200
+++ b/th_datastruct.c	Wed Dec 07 15:03:09 2022 +0200
@@ -589,3 +589,70 @@
 
     return true;
 }
+
+
+int th_ptrlist_init(th_ptrlist_t *list, const size_t ninitial, const size_t ngrow)
+{
+    memset(list, 0, sizeof(*list));
+
+    if (ngrow == 0)
+        return THERR_INVALID_ARGS;
+
+    list->nitems = 0;
+    list->nallocated = ninitial;
+    list->ngrow = ngrow;
+
+    if ((list->items = th_malloc(list->nallocated * sizeof(void *))) == NULL)
+        return THERR_MALLOC;
+
+    return THERR_OK;
+}
+
+
+int th_ptrlist_new(th_ptrlist_t **list, const size_t ninitial, const size_t ngrow)
+{
+    int res;
+
+    if ((*list = th_malloc0(sizeof(th_ptrlist_t))) == NULL)
+        return THERR_MALLOC;
+
+    if ((res = th_ptrlist_init(*list, ninitial, ngrow)) != THERR_OK)
+    {
+        th_free(*list);
+        return res;
+    }
+
+    (*list)->is_allocated = true;
+
+    return THERR_OK;
+}
+
+
+int th_ptrlist_append(th_ptrlist_t *list, void *str)
+{
+    if (list->nitems + 1 >= list->nallocated)
+    {
+        list->nallocated += list->ngrow;
+        if ((list->items = th_realloc(list->items, list->nallocated * sizeof(void *))) == NULL)
+            return THERR_MALLOC;
+    }
+
+    list->items[list->nitems++] = str;
+
+    return THERR_OK;
+}
+
+
+void th_ptrlist_free(th_ptrlist_t *list, void (*mdeallocator)(void *data))
+{
+    if (mdeallocator != NULL)
+    {
+        for (size_t i = 0; i < list->nitems; i++)
+            mdeallocator(list->items[i]);
+    }
+
+    th_free(list->items);
+
+    if (list->is_allocated)
+        th_free(list);
+}
--- a/th_datastruct.h	Wed Dec 07 12:14:39 2022 +0200
+++ b/th_datastruct.h	Wed Dec 07 15:03:09 2022 +0200
@@ -116,6 +116,23 @@
 bool    th_growbuf_put_u32_le(th_growbuf_t *buf, const uint32_t val);
 
 
+/** @brief
+ * Growing pointerlist/array structure
+ */
+typedef struct
+{
+    bool is_allocated;
+    size_t nitems, nallocated, ngrow;
+    void **items;
+} th_ptrlist_t;
+
+
+int     th_ptrlist_init(th_ptrlist_t *list, const size_t ninitial, const size_t ngrow);
+int     th_ptrlist_new(th_ptrlist_t **list, const size_t ninitial, const size_t ngrow);
+int     th_ptrlist_append(th_ptrlist_t *list, void *str);
+void    th_ptrlist_free(th_ptrlist_t *list, void (*mdeallocator)(void *data));
+
+
 #ifdef __cplusplus
 }
 #endif