From: Lennart Poettering Date: Mon, 26 Jun 2023 15:15:28 +0000 (+0200) Subject: string-util: add strextendn() helper X-Git-Tag: v254-rc1~86^2~5 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=6b9f600772c7f9b86c437c72d9a8e9ae6e8d9596;p=thirdparty%2Fsystemd.git string-util: add strextendn() helper --- diff --git a/src/basic/string-util.c b/src/basic/string-util.c index 1eedcb66f7c..d5e1d4e92dd 100644 --- a/src/basic/string-util.c +++ b/src/basic/string-util.c @@ -891,6 +891,33 @@ oom: return -ENOMEM; } +char *strextendn(char **x, const char *s, size_t l) { + assert(x); + assert(s || l == 0); + + if (l == SIZE_MAX) + l = strlen_ptr(s); + else if (l > 0) + l = strnlen(s, l); /* ignore trailing noise */ + + if (l > 0 || !*x) { + size_t q; + char *m; + + q = strlen_ptr(*x); + m = realloc(*x, q + l + 1); + if (!m) + return NULL; + + memcpy_safe(m + q, s, l); + m[q + l] = 0; + + *x = m; + } + + return *x; +} + char *strrep(const char *s, unsigned n) { char *r, *p; size_t l; diff --git a/src/basic/string-util.h b/src/basic/string-util.h index 0ff5b46bba9..ce6ea64bb91 100644 --- a/src/basic/string-util.h +++ b/src/basic/string-util.h @@ -186,6 +186,8 @@ char *strextend_with_separator_internal(char **x, const char *separator, ...) _s #define strextend_with_separator(x, separator, ...) strextend_with_separator_internal(x, separator, __VA_ARGS__, NULL) #define strextend(x, ...) strextend_with_separator_internal(x, NULL, __VA_ARGS__, NULL) +char *strextendn(char **x, const char *s, size_t l); + int strextendf_with_separator(char **x, const char *separator, const char *format, ...) _printf_(3,4); #define strextendf(x, ...) strextendf_with_separator(x, NULL, __VA_ARGS__) diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index e8fcc5a13c9..6ec70054e78 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -1274,4 +1274,22 @@ TEST(version_is_valid) { assert_se(version_is_valid("6.2.12-300.fc38.x86_64")); } +TEST(strextendn) { + _cleanup_free_ char *x = NULL; + + assert_se(streq_ptr(strextendn(&x, NULL, 0), "")); + x = mfree(x); + + assert_se(streq_ptr(strextendn(&x, "", 0), "")); + x = mfree(x); + + assert_se(streq_ptr(strextendn(&x, "xxx", 3), "xxx")); + assert_se(streq_ptr(strextendn(&x, "xxx", 3), "xxxxxx")); + assert_se(streq_ptr(strextendn(&x, "...", 1), "xxxxxx.")); + assert_se(streq_ptr(strextendn(&x, "...", 2), "xxxxxx...")); + assert_se(streq_ptr(strextendn(&x, "...", 3), "xxxxxx......")); + assert_se(streq_ptr(strextendn(&x, "...", 4), "xxxxxx.........")); + x = mfree(x); +} + DEFINE_TEST_MAIN(LOG_DEBUG);