string-util: make split_pair() return parameters optional

This commit is contained in:
Lennart Poettering
2026-06-19 23:05:36 +02:00
parent e641f37499
commit 4552dce3b5
2 changed files with 33 additions and 10 deletions
+16 -10
View 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;
}
+17
View 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) {