[misc] Add an in-place string replacement function

This commit is contained in:
ejurgensen 2020-02-11 14:12:04 +01:00
parent d90cf953dc
commit d86ca1176d
2 changed files with 46 additions and 3 deletions

View File

@ -380,6 +380,49 @@ safe_snprintf_cat(char *dst, size_t n, const char *fmt, ...)
return -1;
}
int
safe_snreplace(char *s, size_t sz, const char *pattern, const char *replacement)
{
char *ptr;
char *src;
char *dst;
size_t num;
if (!s)
return -1;
if (!pattern || !replacement)
return 0;
size_t p_len = strlen(pattern);
size_t r_len = strlen(replacement);
size_t s_len = strlen(s) + 1; // Incl terminator
ptr = s;
while ((ptr = strstr(ptr, pattern)))
{
// We will move the part of the string after the pattern from src to dst
src = ptr + p_len;
dst = ptr + r_len;
num = s_len - (src - s); // Number of bytes w/terminator we need to move
if (dst + num > s + sz)
return -1; // Not enough room
// Shift everything after the pattern to the right, use memmove since
// there might be an overlap
memmove(dst, src, num);
// Write replacement, no null terminater
memcpy(ptr, replacement, r_len);
// Advance ptr to avoid infinite looping
ptr = dst;
}
return 0;
}
/* Key/value functions */
struct keyval *
@ -387,7 +430,7 @@ keyval_alloc(void)
{
struct keyval *kv;
kv = (struct keyval *)malloc(sizeof(struct keyval));
kv = calloc(1, sizeof(struct keyval));
if (!kv)
{
DPRINTF(E_LOG, L_MISC, "Out of memory for keyval alloc\n");
@ -395,8 +438,6 @@ keyval_alloc(void)
return NULL;
}
memset(kv, 0, sizeof(struct keyval));
return kv;
}

View File

@ -87,6 +87,8 @@ safe_asprintf(const char *fmt, ...) __attribute__ ((format (printf, 1, 2)));
int
safe_snprintf_cat(char *dst, size_t n, const char *fmt, ...) __attribute__ ((format (printf, 3, 4)));
int
safe_snreplace(char *s, size_t sz, const char *pattern, const char *replacement);
/* Key/value functions */
struct keyval *