string-util: update strreplace() a bit, use GREEDY_REALLOC()

This commit is contained in:
Lennart Poettering 2017-11-21 19:38:49 +01:00
parent 6171b8225f
commit 9d73565ac0
1 changed files with 13 additions and 17 deletions

View File

@ -603,26 +603,26 @@ char* strshorten(char *s, size_t l) {
} }
char *strreplace(const char *text, const char *old_string, const char *new_string) { char *strreplace(const char *text, const char *old_string, const char *new_string) {
size_t l, old_len, new_len, allocated = 0;
char *t, *ret = NULL;
const char *f; const char *f;
char *t, *r;
size_t l, old_len, new_len;
assert(text);
assert(old_string); assert(old_string);
assert(new_string); assert(new_string);
if (!text)
return NULL;
old_len = strlen(old_string); old_len = strlen(old_string);
new_len = strlen(new_string); new_len = strlen(new_string);
l = strlen(text); l = strlen(text);
r = new(char, l+1); if (!GREEDY_REALLOC(ret, allocated, l+1))
if (!r)
return NULL; return NULL;
f = text; f = text;
t = r; t = ret;
while (*f) { while (*f) {
char *a;
size_t d, nl; size_t d, nl;
if (!startswith(f, old_string)) { if (!startswith(f, old_string)) {
@ -630,25 +630,21 @@ char *strreplace(const char *text, const char *old_string, const char *new_strin
continue; continue;
} }
d = t - r; d = t - ret;
nl = l - old_len + new_len; nl = l - old_len + new_len;
a = realloc(r, nl + 1);
if (!a) if (!GREEDY_REALLOC(ret, allocated, nl + 1))
goto oom; return mfree(ret);
l = nl; l = nl;
r = a; t = ret + d;
t = r + d;
t = stpcpy(t, new_string); t = stpcpy(t, new_string);
f += old_len; f += old_len;
} }
*t = 0; *t = 0;
return r; return ret;
oom:
return mfree(r);
} }
char *strip_tab_ansi(char **ibuf, size_t *_isz) { char *strip_tab_ansi(char **ibuf, size_t *_isz) {