strv: fix STRV_FOREACH_BACKWARDS() to be a single statement only
authorLennart Poettering <lennart@poettering.net>
Fri, 26 Aug 2016 17:18:15 +0000 (19:18 +0200)
committerLennart Poettering <lennart@poettering.net>
Fri, 7 Oct 2016 18:14:38 +0000 (20:14 +0200)
Let's make sure people invoking STRV_FOREACH_BACKWARDS() as a single statement
of an if statement don't fall into a trap, and find the tail for the list via
strv_length().

src/basic/strv.h
src/test/test-strv.c

index fec2597..385ad17 100644 (file)
@@ -96,10 +96,13 @@ bool strv_overlap(char **a, char **b) _pure_;
 #define STRV_FOREACH(s, l)                      \
         for ((s) = (l); (s) && *(s); (s)++)
 
-#define STRV_FOREACH_BACKWARDS(s, l)            \
-        STRV_FOREACH(s, l)                      \
-                ;                               \
-        for ((s)--; (l) && ((s) >= (l)); (s)--)
+#define STRV_FOREACH_BACKWARDS(s, l)                                \
+        for (s = ({                                                 \
+                        char **_l = l;                              \
+                        _l ? _l + strv_length(_l) - 1U : NULL;      \
+                        });                                         \
+             (l) && ((s) >= (l));                                   \
+             (s)--)
 
 #define STRV_FOREACH_PAIR(x, y, l)               \
         for ((x) = (l), (y) = (x+1); (x) && *(x) && *(y); (x) += 2, (y) = (x + 1))
index ce20f2d..88da69e 100644 (file)
@@ -453,9 +453,14 @@ static void test_strv_foreach_backwards(void) {
 
         assert_se(a);
 
-        STRV_FOREACH_BACKWARDS(check, a) {
+        STRV_FOREACH_BACKWARDS(check, a)
                 assert_se(streq_ptr(*check, input_table_multiple[i--]));
-        }
+
+        STRV_FOREACH_BACKWARDS(check, (char**) NULL)
+                assert_not_reached("Let's see that we check empty strv right, too.");
+
+        STRV_FOREACH_BACKWARDS(check, (char**) { NULL })
+                assert_not_reached("Let's see that we check empty strv right, too.");
 }
 
 static void test_strv_foreach_pair(void) {