From 591f6ecfdf54dc7212260d23bdd5114c66317c62 Mon Sep 17 00:00:00 2001 From: Sebastian Reimers Date: Mon, 17 Mar 2025 20:20:15 +0100 Subject: [PATCH 1/2] list: optimize list_count Instead of iterating over the list, count items separately --- include/re_list.h | 3 ++- src/list/list.c | 19 +++++++++---------- 2 files changed, 11 insertions(+), 11 deletions(-) diff --git a/include/re_list.h b/include/re_list.h index 8cf08f1a8..69ea1f0e5 100644 --- a/include/re_list.h +++ b/include/re_list.h @@ -21,10 +21,11 @@ struct le { struct list { struct le *head; /**< First list element */ struct le *tail; /**< Last list element */ + size_t cnt; /**< Number of elements */ }; /** Linked list Initializer */ -#define LIST_INIT {NULL, NULL} +#define LIST_INIT {NULL, NULL, 0} /** diff --git a/src/list/list.c b/src/list/list.c index c86889d06..3779f337a 100644 --- a/src/list/list.c +++ b/src/list/list.c @@ -25,6 +25,7 @@ void list_init(struct list *list) list->head = NULL; list->tail = NULL; + list->cnt = 0; } @@ -109,6 +110,7 @@ void list_append(struct list *list, struct le *le, void *data) list->tail->next = le; list->tail = le; + ++list->cnt; } @@ -141,6 +143,7 @@ void list_prepend(struct list *list, struct le *le, void *data) list->tail = le; list->head = le; + ++list->cnt; } @@ -174,6 +177,7 @@ void list_insert_before(struct list *list, struct le *le, struct le *ile, ile->data = data; le->prev = ile; + ++list->cnt; } @@ -207,6 +211,8 @@ void list_insert_after(struct list *list, struct le *le, struct le *ile, ile->data = data; le->next = ile; + + ++list->cnt; } @@ -271,6 +277,8 @@ void list_unlink(struct le *le) le->next = NULL; le->prev = NULL; le->list = NULL; + + --list->cnt; } @@ -399,14 +407,5 @@ struct le *list_tail(const struct list *list) */ uint32_t list_count(const struct list *list) { - uint32_t n = 0; - struct le *le; - - if (!list) - return 0; - - for (le = list->head; le; le = le->next) - ++n; - - return n; + return list ? (uint32_t)list->cnt : 0; } From 9788700bf191ad5743288f86b49e002c30fd81f8 Mon Sep 17 00:00:00 2001 From: Sebastian Reimers Date: Tue, 18 Mar 2025 20:47:58 +0100 Subject: [PATCH 2/2] prevent possible underflow --- src/list/list.c | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/list/list.c b/src/list/list.c index 3779f337a..9c8152c36 100644 --- a/src/list/list.c +++ b/src/list/list.c @@ -278,7 +278,8 @@ void list_unlink(struct le *le) le->prev = NULL; le->list = NULL; - --list->cnt; + if (list->cnt) + --list->cnt; }