#include <sys/cdefs.h>
__FBSDID("$FreeBSD: src/usr.bin/xargs/strnsubst.c,v 1.7 2004/10/18 15:40:47 cperciva Exp $");
#include <err.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
void strnsubst(char **, const char *, const char *, size_t);
void
strnsubst(char **str, const char *match, const char *replstr, size_t maxsize)
{
char *s1, *s2, *this;
s1 = *str;
if (s1 == NULL)
return;
s2 = calloc(maxsize, 1);
if (s2 == NULL)
err(1, "calloc");
if (replstr == NULL)
replstr = "";
if (match == NULL || replstr == NULL || maxsize == strlen(s1)) {
strlcpy(s2, s1, maxsize);
goto done;
}
for (;;) {
this = strstr(s1, match);
if (this == NULL)
break;
if ((strlen(s2) + strlen(s1) + strlen(replstr) -
strlen(match) + 1) > maxsize) {
strlcat(s2, s1, maxsize);
goto done;
}
strncat(s2, s1, (uintptr_t)this - (uintptr_t)s1);
strcat(s2, replstr);
s1 = this + strlen(match);
}
strcat(s2, s1);
done:
*str = s2;
return;
}
#ifdef TEST
#include <stdio.h>
int
main(void)
{
char *x, *y, *z, *za;
x = "{}%$";
strnsubst(&x, "%$", "{} enpury!", 255);
y = x;
strnsubst(&y, "}{}", "ybir", 255);
z = y;
strnsubst(&z, "{", "v ", 255);
za = z;
strnsubst(&z, NULL, za, 255);
if (strcmp(z, "v ybir enpury!") == 0)
printf("strnsubst() seems to work!\n");
else
printf("strnsubst() is broken.\n");
printf("%s\n", z);
free(x);
free(y);
free(z);
free(za);
return 0;
}
#endif