]> git.saurik.com Git - apple/shell_cmds.git/blob - xargs/strnsubst.c
fa8d93375bc19c856eef63b8bfc5277392eae9c5
[apple/shell_cmds.git] / xargs / strnsubst.c
1 /* $xMach: strnsubst.c,v 1.3 2002/02/23 02:10:24 jmallett Exp $ */
2
3 /*
4 * Copyright (c) 2002 J. Mallett. All rights reserved.
5 * You may do whatever you want with this file as long as
6 * the above copyright and this notice remain intact, along
7 * with the following statement:
8 * For the man who taught me vi, and who got too old, too young.
9 */
10
11 #include <sys/cdefs.h>
12 __RCSID("$FreeBSD: src/usr.bin/xargs/strnsubst.c,v 1.6 2002/06/22 12:58:42 jmallett Exp $");
13
14 #include <err.h>
15 #include <stdlib.h>
16 #include <string.h>
17 #include <unistd.h>
18
19 void strnsubst(char **, const char *, const char *, size_t);
20
21 /*
22 * Replaces str with a string consisting of str with match replaced with
23 * replstr as many times as can be done before the constructed string is
24 * maxsize bytes large. It does not free the string pointed to by str, it
25 * is up to the calling program to be sure that the original contents of
26 * str as well as the new contents are handled in an appropriate manner.
27 * If replstr is NULL, then that internally is changed to a nil-string, so
28 * that we can still pretend to do somewhat meaningful substitution.
29 * No value is returned.
30 */
31 void
32 strnsubst(char **str, const char *match, const char *replstr, size_t maxsize)
33 {
34 char *s1, *s2, *this;
35
36 s1 = *str;
37 if (s1 == NULL)
38 return;
39 s2 = calloc(maxsize, 1);
40 if (s2 == NULL)
41 err(1, "calloc");
42
43 if (replstr == NULL)
44 replstr = "";
45
46 if (match == NULL || replstr == NULL || maxsize == strlen(s1)) {
47 strncpy(s2, s1, maxsize);
48 s2[maxsize - 1] = '\0';
49 goto done;
50 }
51
52 for (;;) {
53 this = strstr(s1, match);
54 if (this == NULL)
55 break;
56 if ((strlen(s2) + ((uintptr_t)this - (uintptr_t)s1) +
57 (strlen(replstr) - 1)) > maxsize && *replstr != '\0') {
58 strncat(s2, s1, maxsize);
59 s2[maxsize - 1] = '\0';
60 goto done;
61 }
62 strncat(s2, s1, (uintptr_t)this - (uintptr_t)s1);
63 strcat(s2, replstr);
64 s1 = this + strlen(match);
65 }
66 strcat(s2, s1);
67 done:
68 *str = s2;
69 return;
70 }
71
72 #ifdef TEST
73 #include <stdio.h>
74
75 int
76 main(void)
77 {
78 char *x, *y, *z, *za;
79
80 x = "{}%$";
81 strnsubst(&x, "%$", "{} enpury!", 255);
82 y = x;
83 strnsubst(&y, "}{}", "ybir", 255);
84 z = y;
85 strnsubst(&z, "{", "v ", 255);
86 za = z;
87 strnsubst(&z, NULL, za, 255);
88 if (strcmp(z, "v ybir enpury!") == 0)
89 printf("strnsubst() seems to work!\n");
90 else
91 printf("strnsubst() is broken.\n");
92 printf("%s\n", z);
93 free(x);
94 free(y);
95 free(z);
96 free(za);
97 return 0;
98 }
99 #endif