From 55cb63bf6e5878e25ce7934b57b7214a9f0cc161 Mon Sep 17 00:00:00 2001 From: Lennart Poettering Date: Wed, 29 Sep 2021 00:13:12 +0200 Subject: [PATCH] list: add LIST_POP() helper that pops the first item off a linked list --- src/basic/list.h | 9 +++++++++ src/test/test-list.c | 9 +++++++++ 2 files changed, 18 insertions(+) diff --git a/src/basic/list.h b/src/basic/list.h index e488fff9f02..effee0e435e 100644 --- a/src/basic/list.h +++ b/src/basic/list.h @@ -181,3 +181,12 @@ } \ (b) = NULL; \ } while (false) + +#define LIST_POP(name, a) \ + ({ \ + typeof(a)* _a = &(a); \ + typeof(a) _p = *_a; \ + if (_p) \ + LIST_REMOVE(name, *_a, _p); \ + _p; \ + }) diff --git a/src/test/test-list.c b/src/test/test-list.c index a41f23ab3ed..25cc55a998d 100644 --- a/src/test/test-list.c +++ b/src/test/test-list.c @@ -247,5 +247,14 @@ int main(int argc, const char *argv[]) { assert_se(head == NULL); + LIST_PREPEND(item, head, items + 0); + LIST_PREPEND(item, head, items + 1); + LIST_PREPEND(item, head, items + 2); + + assert_se(LIST_POP(item, head) == items + 2); + assert_se(LIST_POP(item, head) == items + 1); + assert_se(LIST_POP(item, head) == items + 0); + assert_se(LIST_POP(item, head) == NULL); + return 0; } -- 2.47.3