]> git.ipfire.org Git - pakfire.git/commitdiff
string: Refactor replacement function once again
authorMichael Tremer <michael.tremer@ipfire.org>
Mon, 2 Oct 2023 15:53:09 +0000 (15:53 +0000)
committerMichael Tremer <michael.tremer@ipfire.org>
Mon, 2 Oct 2023 15:53:09 +0000 (15:53 +0000)
Signed-off-by: Michael Tremer <michael.tremer@ipfire.org>
src/libpakfire/string.c

index f4991c8ed9d47aff68cb16474ddea83244544658..330abc917d183965aa51bf1ef8703a6d94e52e45 100644 (file)
@@ -153,9 +153,28 @@ int pakfire_string_partition(const char* s, const char* delim, char** s1, char**
        return 0;
 }
 
+static int pakfire_string_append(char** buffer, const char* s, const size_t l) {
+       int r;
+
+       // Check how long the string is that we are holding
+       size_t length = (buffer && *buffer) ? strlen(*buffer) : 0;
+
+       // Resize the buffer
+       *buffer = realloc(*buffer, length + l + 1);
+       if (!*buffer)
+               return -errno;
+
+       // Append the new string
+       r = snprintf(*buffer + length, l + 1, "%s", s);
+       if (r < 0)
+               return r;
+
+       return 0;
+}
+
 char* pakfire_string_replace(const char* s, const char* pattern, const char* repl) {
        const char* m = NULL;
-       char* buffer = "";
+       char* buffer = NULL;
        size_t l = 0;
        int r;
 
@@ -170,16 +189,16 @@ char* pakfire_string_replace(const char* s, const char* pattern, const char* rep
                repl = "";
 
        const size_t pattern_length = strlen(pattern);
+       const size_t repl_length = strlen(repl);
 
        // Walk through the string...
        for (const char* p = s; *p;) {
                // Search for the pattern
                m = strstr(p, pattern);
 
-               // Pattern does not exist in the remaining string
                if (!m) {
                        // Copy the remaining string
-                       r = asprintf(&buffer, "%s%s", buffer, p);
+                       r = pakfire_string_append(&buffer, p, strlen(p));
                        if (r < 0)
                                goto ERROR;
 
@@ -189,8 +208,12 @@ char* pakfire_string_replace(const char* s, const char* pattern, const char* rep
                // Determine the length of the string up to the match
                l = m - p;
 
-               // Copy the read string up to pattern and the replacement into the buffer
-               r = asprintf(&buffer, "%s%.*s%s", buffer, (int)l, p, repl);
+               // Copy the read string up to pattern
+               r = pakfire_string_append(&buffer, p, l);
+               if (r < 0)
+                       goto ERROR;
+
+               r = pakfire_string_append(&buffer, repl, repl_length);
                if (r < 0)
                        goto ERROR;