From bec2d50c843ec4fd98bbbb212848ce4f24b96ebb Mon Sep 17 00:00:00 2001 From: 3gg <3gg@shellblade.net> Date: Sat, 15 Jun 2024 11:43:10 -0700 Subject: More convenient list iteration. --- list/include/list.h | 44 ++++++++++++++++++++++---------------------- 1 file changed, 22 insertions(+), 22 deletions(-) (limited to 'list/include/list.h') diff --git a/list/include/list.h b/list/include/list.h index facf820..24291e1 100644 --- a/list/include/list.h +++ b/list/include/list.h @@ -5,15 +5,15 @@ #include #include -#define DEF_LIST(type) \ - typedef struct type##_node { \ +#define DEF_LIST(name, type) \ + typedef struct name##_node { \ type val; \ - struct type##_node* prev; \ - struct type##_node* next; \ - } type##_node; \ - typedef struct type##_list { \ - type##_node* head; \ - } type##_list; + struct name##_node* prev; \ + struct name##_node* next; \ + } name##_node; \ + typedef struct name##_list { \ + name##_node* head; \ + } name##_list; static inline void* alloc(size_t size) { void* ptr = calloc(1, size); @@ -35,7 +35,7 @@ static inline void* alloc(size_t size) { list.head = 0; /// Prepend a value to the list. -#define list_push(list, value) \ +#define list_add(list, value) \ { \ __typeof__(list.head) node = alloc(sizeof(*list.head)); \ node->val = value; \ @@ -86,13 +86,13 @@ static inline void* alloc(size_t size) { /// /// Use 'value' to refer to the address of the current node's value during /// iteration. -#define list_foreach(list, body) \ +#define list_foreach(list, value, body) \ { \ - __typeof__(list.head) node = list.head; \ - while (node) { \ - const __typeof__(node->val)* value = &node->val; \ + __typeof__(list.head)* pNode = &list.head; \ + while (*pNode) { \ + __typeof__((*pNode)->val) value = (*pNode)->val; \ body; \ - node = node->next; \ + pNode = &(*pNode)->next; \ } \ } @@ -100,12 +100,12 @@ static inline void* alloc(size_t size) { /// /// Use 'value' to refer to the address of the current node's value during /// iteration. -#define list_foreach_mut(list, body) \ - { \ - __typeof__(list.head) node = list.head; \ - while (node) { \ - __typeof__(node->val)* value = &node->val; \ - body; \ - node = node->next; \ - } \ +#define list_foreach_mut(list, value, body) \ + { \ + __typeof__(list.head) node = list.head; \ + while (node) { \ + __typeof__(node->val) value = node->val; \ + body; \ + node = node->next; \ + } \ } -- cgit v1.2.3