From b40694f5fc21317af617f37bb03304c84ca993c8 Mon Sep 17 00:00:00 2001 From: Mike Yuan Date: Mon, 10 Feb 2025 19:03:08 +0100 Subject: [PATCH] string-util: introduce strprepend() helper --- src/basic/string-util.c | 14 ++++++++++++++ src/basic/string-util.h | 2 ++ src/test/test-string-util.c | 13 +++++++++++++ 3 files changed, 29 insertions(+) diff --git a/src/basic/string-util.c b/src/basic/string-util.c index b2919164d6a..dace8a606d5 100644 --- a/src/basic/string-util.c +++ b/src/basic/string-util.c @@ -46,6 +46,20 @@ char* first_word(const char *s, const char *word) { return (char*) nw; } +char* strprepend(char **x, const char *s) { + assert(x); + + if (isempty(s) && *x) + return *x; + + char *p = strjoin(strempty(s), *x); + if (!p) + return NULL; + + free_and_replace(*x, p); + return *x; +} + char* strnappend(const char *s, const char *suffix, size_t b) { size_t a; char *r; diff --git a/src/basic/string-util.h b/src/basic/string-util.h index 1bcb1c40e32..1b2f0970610 100644 --- a/src/basic/string-util.h +++ b/src/basic/string-util.h @@ -106,6 +106,8 @@ static inline const char* empty_or_dash_to_null(const char *p) { char* first_word(const char *s, const char *word) _pure_; +char* strprepend(char **x, const char *s); + char* strnappend(const char *s, const char *suffix, size_t length); #define strjoin(a, ...) strextend_with_separator_internal(NULL, NULL, a, __VA_ARGS__, NULL) diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index fbfb3990e42..1b447abda91 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -1348,6 +1348,19 @@ TEST(strextendn) { x = mfree(x); } +TEST(strprepend) { + _cleanup_free_ char *x = NULL; + + ASSERT_STREQ(strprepend(&x, NULL), ""); + x = mfree(x); + + ASSERT_STREQ(strprepend(&x, ""), ""); + + ASSERT_STREQ(strprepend(&x, "xxx"), "xxx"); + ASSERT_STREQ(strprepend(&x, "bar"), "barxxx"); + ASSERT_STREQ(strprepend(&x, "foo"), "foobarxxx"); +} + TEST(strlevenshtein) { assert_se(strlevenshtein(NULL, NULL) == 0); assert_se(strlevenshtein("", "") == 0); -- 2.47.3