From: Lennart Poettering Date: Tue, 16 Jun 2026 13:57:32 +0000 (+0200) Subject: string-util: make split_pair() return parameters optional X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=4552dce3b5ce6e1b3a246dba75b975fb7d88d317;p=thirdparty%2Fsystemd.git string-util: make split_pair() return parameters optional --- diff --git a/src/basic/string-util.c b/src/basic/string-util.c index cfeb2e3917a..0484a03473b 100644 --- a/src/basic/string-util.c +++ b/src/basic/string-util.c @@ -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; } diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index 648b8fa839d..9e8776399bb 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -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) {