string-util: add a mechanism for strextend_with_separator() for specifying "ignore" arguments

in strv_new() we have STRV_IGNORE for skipping over an argument in the
argument list. Let's add the same to strextend_with_separator():

strextend_with_separator(&x, "foo", POINTER_MAX, "bar");

will result in "foobar" being appended to "x". (POINTER_MAX Which is
different from NULL, which terminates the argument list).

This is useful for ternary op situations.

(We should probably get rid of STRV_IGNORE and just use POINTER_MAX
everywhere directly, but that's for another time.)
This commit is contained in:
Lennart Poettering
2025-01-15 09:32:44 +01:00
parent 34467ffa3c
commit fd3b7cf772
2 changed files with 17 additions and 0 deletions

View File

@@ -832,6 +832,8 @@ char* strextend_with_separator_internal(char **x, const char *separator, ...) {
t = va_arg(ap, const char *);
if (!t)
break;
if (t == POINTER_MAX)
continue;
n = strlen(t);
@@ -864,6 +866,8 @@ char* strextend_with_separator_internal(char **x, const char *separator, ...) {
t = va_arg(ap, const char *);
if (!t)
break;
if (t == POINTER_MAX)
continue;
if (need_separator && separator)
p = stpcpy(p, separator);

View File

@@ -262,6 +262,12 @@ TEST(strextend) {
ASSERT_STREQ(str, "0123");
assert_se(strextend(&str, "456", "78", "9"));
ASSERT_STREQ(str, "0123456789");
assert_se(strextend(&str, "more", NULL, "huch"));
ASSERT_STREQ(str, "0123456789more");
assert_se(strextend(&str, "MORE", POINTER_MAX, "HUCH"));
ASSERT_STREQ(str, "0123456789moreMOREHUCH");
}
TEST(strextend_with_separator) {
@@ -285,6 +291,9 @@ TEST(strextend_with_separator) {
ASSERT_STREQ(str, "start,,1,234");
assert_se(strextend_with_separator(&str, ";", "more", "5", "678"));
ASSERT_STREQ(str, "start,,1,234;more;5;678");
assert_se(strextend_with_separator(&str, ";", "xxxx", POINTER_MAX, "yyy"));
ASSERT_STREQ(str, "start,,1,234;more;5;678;xxxx;yyy");
}
TEST(strrep) {
@@ -400,6 +409,10 @@ TEST(strjoin) {
actual = strjoin("foo", NULL, "bar");
ASSERT_STREQ(actual, "foo");
free(actual);
actual = strjoin("foo", POINTER_MAX, "bar");
ASSERT_STREQ(actual, "foobar");
free(actual);
}
TEST(strcmp_ptr) {