]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: make split_pair() return parameters optional
authorLennart Poettering <lennart@amutable.com>
Tue, 16 Jun 2026 13:57:32 +0000 (15:57 +0200)
committerLennart Poettering <lennart@amutable.com>
Fri, 19 Jun 2026 21:05:36 +0000 (23:05 +0200)
src/basic/string-util.c
src/test/test-string-util.c

index cfeb2e3917afac2873cdbe3acecb1906c060d788..0484a03473b5299c9ac09cf573b665b86a703b0e 100644 (file)
@@ -1003,23 +1003,29 @@ char* strrep(const char *s, size_t n) {
 int split_pair(const char *s, const char *sep, char **ret_first, char **ret_second) {
         assert(s);
         assert(!isempty(sep));
-        assert(ret_first);
-        assert(ret_second);
 
         const char *x = strstr(s, sep);
         if (!x)
                 return -EINVAL;
 
-        _cleanup_free_ char *a = strndup(s, x - s);
-        if (!a)
-                return -ENOMEM;
+        _cleanup_free_ char *a = NULL;
+        if (ret_first) {
+                a = strndup(s, x - s);
+                if (!a)
+                        return -ENOMEM;
+        }
 
-        _cleanup_free_ char *b = strdup(x + strlen(sep));
-        if (!b)
-                return -ENOMEM;
+        _cleanup_free_ char *b = NULL;
+        if (ret_second) {
+                b = strdup(x + strlen(sep));
+                if (!b)
+                        return -ENOMEM;
+        }
 
-        *ret_first = TAKE_PTR(a);
-        *ret_second = TAKE_PTR(b);
+        if (ret_first)
+                *ret_first = TAKE_PTR(a);
+        if (ret_second)
+                *ret_second = TAKE_PTR(b);
         return 0;
 }
 
index 648b8fa839d0d43800b826e2ae99cd57fa8ac232..9e8776399bbefe42af3df1e0d6ac41907a56db42 100644 (file)
@@ -640,6 +640,23 @@ TEST(split_pair) {
         ASSERT_OK(split_pair("===", "==", &a, &b));
         ASSERT_STREQ(a, "");
         ASSERT_STREQ(b, "=");
+        a = mfree(a);
+        b = mfree(b);
+
+        /* The output parameters are optional */
+        ASSERT_OK(split_pair("foo=bar", "=", NULL, &b));
+        ASSERT_NULL(a);
+        ASSERT_STREQ(b, "bar");
+        b = mfree(b);
+        ASSERT_OK(split_pair("foo=bar", "=", &a, NULL));
+        ASSERT_STREQ(a, "foo");
+        ASSERT_NULL(b);
+        a = mfree(a);
+        ASSERT_OK(split_pair("foo=bar", "=", NULL, NULL));
+        ASSERT_NULL(a);
+        ASSERT_NULL(b);
+        /* ... but the separator must still be present */
+        ASSERT_ERROR(split_pair("foo", "=", NULL, NULL), EINVAL);
 }
 
 TEST(empty_to_null) {