From 4440e3cdf7860a036836216ffa80a6ef82096901 Mon Sep 17 00:00:00 2001 From: Quentin Young Date: Fri, 7 Dec 2018 22:06:42 +0000 Subject: [PATCH] lib: add list_to_array Signed-off-by: Quentin Young --- lib/linklist.c | 15 +++++++++++++++ lib/linklist.h | 20 ++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/lib/linklist.c b/lib/linklist.c index 40c4b27169..43bc709325 100644 --- a/lib/linklist.c +++ b/lib/linklist.c @@ -334,3 +334,18 @@ struct listnode *listnode_add_force(struct list **list, void *val) *list = list_new(); return listnode_add(*list, val); } + +void **list_to_array(struct list *list, void **arr, size_t arrlen) +{ + struct listnode *ln; + void *vp; + size_t idx = 0; + + for (ALL_LIST_ELEMENTS_RO(list, ln, vp)) { + arr[idx++] = vp; + if (idx == arrlen) + break; + } + + return arr; +} diff --git a/lib/linklist.h b/lib/linklist.h index c30d8d314a..c2b289596d 100644 --- a/lib/linklist.h +++ b/lib/linklist.h @@ -239,6 +239,26 @@ extern struct list *list_dup(struct list *l); extern void list_sort(struct list *list, int (*cmp)(const void **, const void **)); +/* + * Convert a list to an array of void pointers. + * + * Starts from the list head and ends either on the last node of the list or + * when the provided array cannot store any more elements. + * + * list + * list to convert + * + * arr + * Pre-allocated array of void * + * + * arrlen + * Number of elements in arr + * + * Returns: + * arr + */ +void **list_to_array(struct list *list, void **arr, size_t arrlen); + /* * Delete a list and NULL its pointer. * -- 2.39.5