]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
string-util: introduce strrepa
authorMike Yuan <me@yhndnzj.com>
Sat, 26 Aug 2023 09:50:24 +0000 (17:50 +0800)
committerMike Yuan <me@yhndnzj.com>
Sat, 2 Sep 2023 14:59:15 +0000 (22:59 +0800)
src/basic/string-util.h
src/test/test-string-util.c

index 73d586d4c54c849687bb4f0cff489b68b5c30135..72f791f6ccb92c2905570e6b73684173275b6c10 100644 (file)
@@ -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);
index b5f0008d76bef481b49198af55205965f2c8ec46..a8fd45df733e77aed6d42e46a971e725c11fb53c 100644 (file)
@@ -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) {