From e719ba239f5ac4bf12db2e454a5d330481ed249d Mon Sep 17 00:00:00 2001 From: Sayooj K Karun Date: Thu, 12 Jun 2025 17:44:14 +0530 Subject: [PATCH] include: zephyr: sys: simplify MIN_HEAP_FOREACH macro Refactor the `MIN_HEAP_FOREACH` macro to use a cleaner for-loop style removing the need for a third `body` argument. Update the sample application with the new macro changes. Signed-off-by: Sayooj K Karun --- .clang-format | 1 + include/zephyr/sys/min_heap.h | 15 +++++---------- samples/data_structures/min-heap/src/main.c | 8 ++++---- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/.clang-format b/.clang-format index 11054457bc3..e0982b801ca 100644 --- a/.clang-format +++ b/.clang-format @@ -82,6 +82,7 @@ ForEachMacros: - 'HTTP_SERVICE_FOREACH_RESOURCE' - 'I3C_BUS_FOR_EACH_I3CDEV' - 'I3C_BUS_FOR_EACH_I2CDEV' + - 'MIN_HEAP_FOREACH' IfMacros: - 'CHECKIF' # Disabled for now, see bug https://github.com/zephyrproject-rtos/zephyr/issues/48520 diff --git a/include/zephyr/sys/min_heap.h b/include/zephyr/sys/min_heap.h index eaf5d39fa05..3a1505a37bb 100644 --- a/include/zephyr/sys/min_heap.h +++ b/include/zephyr/sys/min_heap.h @@ -220,23 +220,18 @@ static inline void *min_heap_get_element(const struct min_heap *heap, * * @param heap Pointer to the heap. * @param node_var The loop variable used to reference each node. - * @param body Code block to execute for each node. * * Example: * ``` * void *node; - * MIN_HEAP_FOREACH(&heap, node, { + * MIN_HEAP_FOREACH(&heap, node) { * printk("Value: %d\n", node->value); - * }); + * } * ``` */ -#define MIN_HEAP_FOREACH(heap, node_var, body) \ - do { for (size_t _i = 0; _i < (heap)->size && \ - (((node_var) = min_heap_get_element((heap), _i)) || true); \ - ++_i) { \ - body; \ - } \ - } while (0) +#define MIN_HEAP_FOREACH(heap, node_var) \ + for (size_t _i = 0; \ + _i < (heap)->size && (((node_var) = min_heap_get_element((heap), _i)) || true); ++_i) /** * @} diff --git a/samples/data_structures/min-heap/src/main.c b/samples/data_structures/min-heap/src/main.c index d81284e929d..10ce18fd136 100644 --- a/samples/data_structures/min-heap/src/main.c +++ b/samples/data_structures/min-heap/src/main.c @@ -57,11 +57,11 @@ int main(void) } printk("Heap elements by order of priority:\n"); - MIN_HEAP_FOREACH(&my_heap, elem, { + MIN_HEAP_FOREACH(&my_heap, elem) { struct data *d = elem; printk("key=%d value=%d\n", d->key, d->value); - }); + } printk("Top of heap: "); top = min_heap_peek(&my_heap); @@ -77,11 +77,11 @@ int main(void) } printk("Heap after removal:\n"); - MIN_HEAP_FOREACH(&my_heap, elem, { + MIN_HEAP_FOREACH(&my_heap, elem) { struct data *d = elem; printk("key=%d value=%d\n", d->key, d->value); - }); + } return 0; }