string-util: introduce strprepend() helper

This commit is contained in:
Mike Yuan
2025-02-10 19:39:21 +01:00
parent fd2a114061
commit b40694f5fc
3 changed files with 29 additions and 0 deletions
+14
View File
@@ -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;
+2
View File
@@ -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)
+13
View File
@@ -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);