# HG changeset patch # User Matti Hamalainen # Date 1670418189 -7200 # Node ID ca837a4417f55f08c63a15af5f3d9b1080855906 # Parent 31bc1ed07cf53b915842ef4be0d669c2484474c5 Add simple growing pointerlist data stucture implementation. diff -r 31bc1ed07cf5 -r ca837a4417f5 th_datastruct.c --- 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); +} diff -r 31bc1ed07cf5 -r ca837a4417f5 th_datastruct.h --- 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