add cx_foreach macro

Sat, 22 Jan 2022 19:04:32 +0100

author
Mike Becker <universe@uap-core.de>
date
Sat, 22 Jan 2022 19:04:32 +0100
changeset 496
1a07e24801a9
parent 495
2856c74e18ba
child 497
b182a8b8a1af

add cx_foreach macro

src/cx/iterator.h file | annotate | diff | comparison | revisions
test/test_list.c file | annotate | diff | comparison | revisions
--- a/src/cx/iterator.h	Sat Jan 22 18:49:06 2022 +0100
+++ b/src/cx/iterator.h	Sat Jan 22 19:04:32 2022 +0100
@@ -100,7 +100,7 @@
  *
  * This is especially false for past-the-end iterators.
  *
- * @param iter the iterator
+ * @param iter a pointer to the iterator
  * @return true iff the iterator points to valid data
  */
 __attribute__ ((__nonnull__))
@@ -113,7 +113,7 @@
  *
  * The behavior is undefined if this iterator is invalid.
  *
- * @param iter the iterator
+ * @param iter a pointer to the iterator
  * @return a pointer to the current element
  */
 __attribute__ ((__nonnull__))
@@ -124,11 +124,20 @@
 /**
  * Advances the iterator to the next element.
  *
- * @param iter the iterator
+ * @param iter a pointer to the iterator
  */
 __attribute__ ((__nonnull__))
 static inline void cxIteratorNext(CxIterator *iter) {
     iter->next(iter);
 }
 
+/**
+ * Loops over an iterator.
+ * @param type the type of the elements
+ * @param elem the name of the iteration variable
+ * @param iter the iterator
+ */
+#define cx_foreach(type, elem, iter) \
+for (type *elem; cxIteratorValid(&iter) && (elem = cxIteratorCurrent(&iter)) != NULL ; cxIteratorNext(&iter)) // NOLINT(bugprone-macro-parentheses)
+
 #endif /* UCX_ITERATOR_H */
--- a/test/test_list.c	Sat Jan 22 18:49:06 2022 +0100
+++ b/test/test_list.c	Sat Jan 22 19:04:32 2022 +0100
@@ -761,9 +761,9 @@
 
 void test_hl_linked_list_iterator_impl(CxList list) {
     int i = 0;
-    for (CxIterator iter = cxListBegin(list); cxIteratorValid(&iter); cxIteratorNext(&iter)) {
+    CxIterator iter = cxListBegin(list);
+    cx_foreach(int, x, iter) {
         CU_ASSERT_EQUAL(iter.index, (size_t) (i + 1) / 2)
-        int *x = cxIteratorCurrent(&iter);
         CU_ASSERT_EQUAL(*x, i)
         if (i % 2 == 1) iter.remove = true;
         i++;

mercurial