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;
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;
// 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;