]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
strv: add new macro STARTSWITH_SET()
authorLennart Poettering <lennart@poettering.net>
Fri, 23 Nov 2018 15:27:15 +0000 (16:27 +0100)
committerLennart Poettering <lennart@poettering.net>
Mon, 26 Nov 2018 13:06:01 +0000 (14:06 +0100)
This is to startswith() what PATH_STARTSWITH_SET() is to
path_startswith().

Or in other words, checks if the specified string has any of the listed
prefixes, and if so, returns the remainder of the string.

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

index 5f1803d87db593b85e8664e174f9d58433aea55a..aa4cd4aacabbe665c5646d4c7c033850b9612894 100644 (file)
@@ -144,6 +144,18 @@ void strv_print(char **l);
                 _x && strv_contains(STRV_MAKE(__VA_ARGS__), _x); \
         })
 
+#define STARTSWITH_SET(p, ...)                                  \
+        ({                                                      \
+                const char *_p = (p);                           \
+                char  *_found = NULL, **_i;                     \
+                STRV_FOREACH(_i, STRV_MAKE(__VA_ARGS__)) {      \
+                        _found = startswith(_p, *_i);           \
+                        if (_found)                             \
+                                break;                          \
+                }                                               \
+                _found;                                         \
+        })
+
 #define FOREACH_STRING(x, ...)                               \
         for (char **_l = ({                                  \
                 char **_ll = STRV_MAKE(__VA_ARGS__);         \
index 63757afdce479ec38aa6da83def82692a546432c..31ef1abb4441c7f88c8054d44e957c0fa1f42e6e 100644 (file)
@@ -56,6 +56,20 @@ static void test_strptr_in_set(void) {
         assert_se(!STRPTR_IN_SET(NULL, NULL));
 }
 
+static void test_startswith_set(void) {
+        assert_se(!STARTSWITH_SET("foo", "bar", "baz", "waldo"));
+        assert_se(!STARTSWITH_SET("foo", "bar"));
+
+        assert_se(STARTSWITH_SET("abc", "a", "ab", "abc"));
+        assert_se(STARTSWITH_SET("abc", "ax", "ab", "abc"));
+        assert_se(STARTSWITH_SET("abc", "ax", "abx", "abc"));
+        assert_se(!STARTSWITH_SET("abc", "ax", "abx", "abcx"));
+
+        assert_se(streq_ptr(STARTSWITH_SET("foobar", "hhh", "kkk", "foo", "zzz"), "bar"));
+        assert_se(streq_ptr(STARTSWITH_SET("foobar", "hhh", "kkk", "", "zzz"), "foobar"));
+        assert_se(streq_ptr(STARTSWITH_SET("", "hhh", "kkk", "zzz", ""), ""));
+}
+
 static const char* const input_table_multiple[] = {
         "one",
         "two",
@@ -847,6 +861,7 @@ int main(int argc, char *argv[]) {
         test_specifier_printf();
         test_str_in_set();
         test_strptr_in_set();
+        test_startswith_set();
         test_strv_foreach();
         test_strv_foreach_backwards();
         test_strv_foreach_pair();