xref: /freebsd/lib/libfigpar/string_m.c (revision 95eb4b873b6a8b527c5bd78d7191975dfca38998)
1 /*-
2  * Copyright (c) 2001-2014 Devin Teske <dteske@FreeBSD.org>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/types.h>
28 
29 #include <ctype.h>
30 #include <errno.h>
31 #include <stdio.h>
32 #include <stdlib.h>
33 #include <string.h>
34 
35 #include "string_m.h"
36 
37 /*
38  * Counts the number of occurrences of one string that appear in the source
39  * string. Return value is the total count.
40  *
41  * An example use would be if you need to know how large a block of memory
42  * needs to be for a replaceall() series.
43  */
44 unsigned int
45 strcount(const char *source, const char *find)
46 {
47 	const char *p = source;
48 	size_t flen;
49 	unsigned int n = 0;
50 
51 	/* Both parameters are required */
52 	if (source == NULL || find == NULL)
53 		return (0);
54 
55 	/* Cache the length of find element */
56 	flen = strlen(find);
57 	if (strlen(source) == 0 || flen == 0)
58 		return (0);
59 
60 	/* Loop until the end of the string */
61 	while (*p != '\0') {
62 		if (strncmp(p, find, flen) == 0) { /* found an instance */
63 			p += flen;
64 			n++;
65 		} else
66 			p++;
67 	}
68 
69 	return (n);
70 }
71 
72 /*
73  * Replaces all occurrences of `find' in `source' with `replace'.
74  *
75  * You should not pass a string constant as the first parameter, it needs to be
76  * a pointer to an allocated block of memory. The block of memory that source
77  * points to should be large enough to hold the result. If the length of the
78  * replacement string is greater than the length of the find string, the result
79  * will be larger than the original source string. To allocate enough space for
80  * the result, use the function strcount() declared above to determine the
81  * number of occurrences and how much larger the block size needs to be.
82  *
83  * If source is not large enough, the application will crash. The return value
84  * is the length (in bytes) of the result.
85  *
86  * When an error occurs, -1 is returned and the global variable errno is set
87  * accordingly. Returns zero on success.
88  */
89 int
90 replaceall(char *source, const char *find, const char *replace)
91 {
92 	char *p;
93 	char *t;
94 	char *temp;
95 	size_t flen;
96 	size_t rlen;
97 	size_t slen;
98 	uint32_t n = 0;
99 
100 	errno = 0; /* reset global error number */
101 
102 	/* Check that we have non-null parameters */
103 	if (source == NULL)
104 		return (0);
105 	if (find == NULL)
106 		return (strlen(source));
107 
108 	/* Cache the length of the strings */
109 	slen = strlen(source);
110 	flen = strlen(find);
111 	rlen = replace ? strlen(replace) : 0;
112 
113 	/* Cases where no replacements need to be made */
114 	if (slen == 0 || flen == 0 || slen < flen)
115 		return (slen);
116 
117 	/* If replace is longer than find, we'll need to create a temp copy */
118 	if (rlen > flen) {
119 		temp = malloc(slen + 1);
120 		if (temp == NULL) /* could not allocate memory */
121 			return (-1);
122 		memcpy(temp, source, slen + 1);
123 	} else
124 		temp = source;
125 
126 	/* Reconstruct the string with the replacements */
127 	p = source; t = temp; /* position elements */
128 
129 	while (*t != '\0') {
130 		if (strncmp(t, find, flen) == 0) {
131 			/* found an occurrence */
132 			for (n = 0; replace && replace[n]; n++)
133 				*p++ = replace[n];
134 			t += flen;
135 		} else
136 			*p++ = *t++; /* copy character and increment */
137 	}
138 
139 	/* Terminate the string */
140 	*p = '\0';
141 
142 	/* Free the temporary allocated memory */
143 	if (temp != source)
144 		free(temp);
145 
146 	/* Return the length of the completed string */
147 	return (strlen(source));
148 }
149 
150 /*
151  * Expands escape sequences in a buffer pointed to by `source'. This function
152  * steps through each character, and converts escape sequences such as "\n",
153  * "\r", "\t" and others into their respective meanings.
154  *
155  * You should not pass a string constant or literal to this function or the
156  * program will likely segmentation fault when it tries to modify the data.
157  *
158  * The string length will either shorten or stay the same depending on whether
159  * any escape sequences were converted but the amount of memory allocated does
160  * not change.
161  *
162  * Interpreted sequences are:
163  *
164  * 	\0NNN	character with octal value NNN (0 to 3 digits)
165  * 	\N	character with octal value N (0 thru 7)
166  * 	\a	alert (BEL)
167  * 	\b	backslash
168  * 	\f	form feed
169  * 	\n	new line
170  * 	\r	carriage return
171  * 	\t	horizontal tab
172  * 	\v	vertical tab
173  * 	\xNN	byte with hexadecimal value NN (1 to 2 digits)
174  *
175  * All other sequences are unescaped (ie. '\"' and '\#').
176  */
177 void strexpand(char *source)
178 {
179 	uint8_t c;
180 	char *chr;
181 	char *pos;
182 	char d[4];
183 
184 	/* Initialize position elements */
185 	pos = chr = source;
186 
187 	/* Loop until we hit the end of the string */
188 	while (*pos != '\0') {
189 		if (*chr != '\\') {
190 			*pos = *chr; /* copy character to current offset */
191 			pos++;
192 			chr++;
193 			continue;
194 		}
195 
196 		/* Replace the backslash with the correct character */
197 		switch (*++chr) {
198 		case 'a': *pos = '\a'; break; /* bell/alert (BEL) */
199 		case 'b': *pos = '\b'; break; /* backspace */
200 		case 'f': *pos = '\f'; break; /* form feed */
201 		case 'n': *pos = '\n'; break; /* new line */
202 		case 'r': *pos = '\r'; break; /* carriage return */
203 		case 't': *pos = '\t'; break; /* horizontal tab */
204 		case 'v': *pos = '\v'; break; /* vertical tab */
205 		case 'x': /* hex value (1 to 2 digits)(\xNN) */
206 			d[2] = '\0'; /* pre-terminate the string */
207 
208 			/* verify next two characters are hex */
209 			d[0] = isxdigit(*(chr+1)) ? *++chr : '\0';
210 			if (d[0] != '\0')
211 				d[1] = isxdigit(*(chr+1)) ? *++chr : '\0';
212 
213 			/* convert the characters to decimal */
214 			c = (uint8_t)strtoul(d, 0, 16);
215 
216 			/* assign the converted value */
217 			*pos = (c != 0 || d[0] == '0') ? c : *++chr;
218 			break;
219 		case '0': /* octal value (0 to 3 digits)(\0NNN) */
220 			d[3] = '\0'; /* pre-terminate the string */
221 
222 			/* verify next three characters are octal */
223 			d[0] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
224 			    *++chr : '\0';
225 			if (d[0] != '\0')
226 				d[1] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
227 				    *++chr : '\0';
228 			if (d[1] != '\0')
229 				d[2] = (isdigit(*(chr+1)) && *(chr+1) < '8') ?
230 				    *++chr : '\0';
231 
232 			/* convert the characters to decimal */
233 			c = (uint8_t)strtoul(d, 0, 8);
234 
235 			/* assign the converted value */
236 			*pos = c;
237 			break;
238 		default: /* single octal (\0..7) or unknown sequence */
239 			if (isdigit(*chr) && *chr < '8') {
240 				d[0] = *chr;
241 				d[1] = '\0';
242 				*pos = (uint8_t)strtoul(d, 0, 8);
243 			} else
244 				*pos = *chr;
245 		}
246 
247 		/* Increment to next offset, possible next escape sequence */
248 		pos++;
249 		chr++;
250 	}
251 }
252 
253 /*
254  * Expand only the escaped newlines in a buffer pointed to by `source'. This
255  * function steps through each character, and converts the "\n" sequence into
256  * a literal newline and the "\\n" sequence into "\n".
257  *
258  * You should not pass a string constant or literal to this function or the
259  * program will likely segmentation fault when it tries to modify the data.
260  *
261  * The string length will either shorten or stay the same depending on whether
262  * any escaped newlines were converted but the amount of memory allocated does
263  * not change.
264  */
265 void strexpandnl(char *source)
266 {
267 	uint8_t backslash = 0;
268 	char *cp1;
269 	char *cp2;
270 
271 	/* Replace '\n' with literal in dprompt */
272 	cp1 = cp2 = source;
273 	while (*cp2 != '\0') {
274 		*cp1 = *cp2;
275 		if (*cp2 == '\\')
276 			backslash++;
277 		else if (*cp2 != 'n')
278 			backslash = 0;
279 		else if (backslash > 0) {
280 			*(--cp1) = (backslash & 1) == 1 ? '\n' : 'n';
281 			backslash = 0;
282 		}
283 		cp1++;
284 		cp2++;
285 	}
286 	*cp1 = *cp2;
287 }
288 
289 /*
290  * Convert a string to lower case. You should not pass a string constant to
291  * this function. Only pass pointers to allocated memory with null terminated
292  * string data.
293  */
294 void
295 strtolower(char *source)
296 {
297 	char *p = source;
298 
299 	if (source == NULL)
300 		return;
301 
302 	while (*p != '\0') {
303 		*p = tolower(*p);
304 		p++; /* would have just used `*p++' but gcc 3.x warns */
305 	}
306 }
307