From 00614746e9d6bdd5d8960f81f8c6418d0434f715 Mon Sep 17 00:00:00 2001 From: Mike Yuan Date: Sat, 26 Aug 2023 17:50:24 +0800 Subject: [PATCH] string-util: introduce strrepa --- src/basic/string-util.h | 11 +++++++++++ src/test/test-string-util.c | 8 ++++++++ 2 files changed, 19 insertions(+) diff --git a/src/basic/string-util.h b/src/basic/string-util.h index 73d586d4c54..72f791f6ccb 100644 --- a/src/basic/string-util.h +++ b/src/basic/string-util.h @@ -196,6 +196,17 @@ int strextendf_with_separator(char **x, const char *separator, const char *forma char *strrep(const char *s, unsigned n); +#define strrepa(s, n) \ + ({ \ + char *_d_, *_p_; \ + size_t _len_ = strlen(s) * n; \ + _p_ = _d_ = newa(char, _len_ + 1); \ + for (unsigned _i_ = 0; _i_ < n; _i_++) \ + _p_ = stpcpy(_p_, s); \ + *_p_ = 0; \ + _d_; \ + }) + int split_pair(const char *s, const char *sep, char **l, char **r); int free_and_strdup(char **p, const char *s); diff --git a/src/test/test-string-util.c b/src/test/test-string-util.c index b5f0008d76b..a8fd45df733 100644 --- a/src/test/test-string-util.c +++ b/src/test/test-string-util.c @@ -260,6 +260,8 @@ TEST(strextend_with_separator) { TEST(strrep) { _cleanup_free_ char *one = NULL, *three = NULL, *zero = NULL; + char *onea, *threea; + one = strrep("waldo", 1); three = strrep("waldo", 3); zero = strrep("waldo", 0); @@ -267,6 +269,12 @@ TEST(strrep) { assert_se(streq(one, "waldo")); assert_se(streq(three, "waldowaldowaldo")); assert_se(streq(zero, "")); + + onea = strrepa("waldo", 1); + threea = strrepa("waldo", 3); + + assert_se(streq(onea, "waldo")); + assert_se(streq(threea, "waldowaldowaldo")); } TEST(string_has_cc) { -- 2.47.3