From 3b26f79143177d9bd2b95b3173a3978e8894cd84 Mon Sep 17 00:00:00 2001 From: Peter Oberparleiter Date: Mon, 5 Feb 2024 14:40:25 +0100 Subject: [PATCH] libutil: add dynamic array helpers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add helper macros to easily create, enlarge and append new elements to dynamic arrays of arbitrary types. Note: The use of dynamic arrays over lists may be preferable in some cases to reduce complexity, and they may be required in cases where elements need to be addressed directly by index. Usage example: struct { int a; int b; } *array = NULL, element = { 1, 2 }; unsigned int num = 0; util_add_array(&array, &num, element); printf("array[0].a=%d\n", array[0].a); /* array[0].a=1 */ printf("array[0].b=%d\n", array[0].b); /* array[0].b=2 */ Reviewed-by: Jan Höppner Signed-off-by: Peter Oberparleiter Signed-off-by: Steffen Eiden --- include/lib/util_base.h | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) diff --git a/include/lib/util_base.h b/include/lib/util_base.h index 0f4b12c5..e09abd87 100644 --- a/include/lib/util_base.h +++ b/include/lib/util_base.h @@ -14,7 +14,10 @@ #include #include +#include + #include "zt_common.h" +#include "lib/util_libc.h" void util_hexdump(FILE *fh, const char *tag, const void *data, int cnt); void util_hexdump_grp(FILE *fh, const char *tag, const void *data, int group, @@ -37,4 +40,30 @@ static inline void util_ptr_vec_free(void **ptr_vec, int count) free(ptr_vec); } +/* + * Expand size of dynamic array (element_t *) by one element + * + * @param[in,out] array Pointer to array (element_t **) + * @param[in,out] num Pointer to integer containing number of elements + */ +#define util_expand_array(array, num) \ + do { \ + unsigned int __size = sizeof(*(*(array))); \ + *(array) = util_realloc(*(array), ++(*(num)) * __size); \ + memset(&((*(array))[*(num) - 1]), 0, __size); \ + } while (0) + +/* + * Append one element to dynamic array (element_t *) + * + * @param[in,out] array Pointer to array (element_t **) + * @param[in,out] num Pointer to integer containing number of elements + * @param[in] element Element to add (element_t) + */ +#define util_add_array(array, num, element) \ + do { \ + util_expand_array(array, num); \ + (*(array))[*(num) - 1] = (element) ; \ + } while (0) + #endif /* LIB_UTIL_BASE_H */