From: Michael Tremer Date: Mon, 2 Oct 2023 15:53:09 +0000 (+0000) Subject: string: Refactor replacement function once again X-Git-Tag: 0.9.30~1567 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=eaba908b61864326a57bbbbc76cfbd8b2b835164;p=pakfire.git string: Refactor replacement function once again Signed-off-by: Michael Tremer --- diff --git a/src/libpakfire/string.c b/src/libpakfire/string.c index f4991c8ed..330abc917 100644 --- a/src/libpakfire/string.c +++ b/src/libpakfire/string.c @@ -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;