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
     1.1 --- a/src/cx/iterator.h	Sat Jan 22 18:49:06 2022 +0100
     1.2 +++ b/src/cx/iterator.h	Sat Jan 22 19:04:32 2022 +0100
     1.3 @@ -100,7 +100,7 @@
     1.4   *
     1.5   * This is especially false for past-the-end iterators.
     1.6   *
     1.7 - * @param iter the iterator
     1.8 + * @param iter a pointer to the iterator
     1.9   * @return true iff the iterator points to valid data
    1.10   */
    1.11  __attribute__ ((__nonnull__))
    1.12 @@ -113,7 +113,7 @@
    1.13   *
    1.14   * The behavior is undefined if this iterator is invalid.
    1.15   *
    1.16 - * @param iter the iterator
    1.17 + * @param iter a pointer to the iterator
    1.18   * @return a pointer to the current element
    1.19   */
    1.20  __attribute__ ((__nonnull__))
    1.21 @@ -124,11 +124,20 @@
    1.22  /**
    1.23   * Advances the iterator to the next element.
    1.24   *
    1.25 - * @param iter the iterator
    1.26 + * @param iter a pointer to the iterator
    1.27   */
    1.28  __attribute__ ((__nonnull__))
    1.29  static inline void cxIteratorNext(CxIterator *iter) {
    1.30      iter->next(iter);
    1.31  }
    1.32  
    1.33 +/**
    1.34 + * Loops over an iterator.
    1.35 + * @param type the type of the elements
    1.36 + * @param elem the name of the iteration variable
    1.37 + * @param iter the iterator
    1.38 + */
    1.39 +#define cx_foreach(type, elem, iter) \
    1.40 +for (type *elem; cxIteratorValid(&iter) && (elem = cxIteratorCurrent(&iter)) != NULL ; cxIteratorNext(&iter)) // NOLINT(bugprone-macro-parentheses)
    1.41 +
    1.42  #endif /* UCX_ITERATOR_H */
     2.1 --- a/test/test_list.c	Sat Jan 22 18:49:06 2022 +0100
     2.2 +++ b/test/test_list.c	Sat Jan 22 19:04:32 2022 +0100
     2.3 @@ -761,9 +761,9 @@
     2.4  
     2.5  void test_hl_linked_list_iterator_impl(CxList list) {
     2.6      int i = 0;
     2.7 -    for (CxIterator iter = cxListBegin(list); cxIteratorValid(&iter); cxIteratorNext(&iter)) {
     2.8 +    CxIterator iter = cxListBegin(list);
     2.9 +    cx_foreach(int, x, iter) {
    2.10          CU_ASSERT_EQUAL(iter.index, (size_t) (i + 1) / 2)
    2.11 -        int *x = cxIteratorCurrent(&iter);
    2.12          CU_ASSERT_EQUAL(*x, i)
    2.13          if (i % 2 == 1) iter.remove = true;
    2.14          i++;

mercurial