Debian Codegraph @

src/regex/regsub.c

raw
1 /*
2 * regsub
3 *
4 * Copyright (c) 1986 by University of Toronto.
5 * Written by Henry Spencer. Not derived from licensed software.
6 *
7 * Permission is granted to anyone to use this software for any
8 * purpose on any computer system, and to redistribute it freely,
9 * subject to the following restrictions:
10 *
11 * 1. The author is not responsible for the consequences of use of
12 * this software, no matter how awful, even if they arise
13 * from defects in it.
14 *
15 * 2. The origin of this software must not be misrepresented, either
16 * by explicit claim or by omission.
17 *
18 * 3. Altered versions must be plainly marked as such, and must not
19 * be misrepresented as being the original software.
20 */
21 /* This is an altered version. It has been modified by David
22 Huggins-Daines <[email protected]> on 2001-10-23 to use a different
23 API and be re-entrant and safe and all that good stuff. */
24 #include "cst_regex.h"
25 #include "cst_string.h"
26 #include "cst_error.h"
27
28 size_t cst_regsub(const cst_regstate *state, const char *in, char *out, size_t max)
29 {
30 const char *src;
31 char *dst;
32 int c, no, len;
33 size_t count;
34
35 if (state == NULL || in == NULL) {
36 cst_errmsg("NULL parm to regsub\n");
37 cst_error();
38 }
39
40 src = in;
41 dst = out;
42 count = 0;
43 while ((c = *src++) != '\0') {
44 if (out && dst + 1 > out + max - 1)
45 break;
46 if (c == '&')
47 no = 0;
48 else if (c == '\\' && '0' <= *src && *src <= '9')
49 no = *src++ - '0';
50 else
51 no = -1;
52
53 if (no < 0) { /* Ordinary character. */
54 if (c == '\\' && (*src == '\\' || *src == '&'))
55 c = *src++;
56 if (out)
57 *dst++ = c;
58 count++;
59 } else if (state->startp[no] != NULL && state->endp[no] != NULL) {
60 len = state->endp[no] - state->startp[no];
61 if (out) {
62 if (dst + len > out + max - 1)
63 len = (out + max - 1) - dst;
64 strncpy(dst, state->startp[no], len);
65 dst += len;
66 /* strncpy hit NUL. */
67 if (len != 0 && *(dst-1) == '\0') {
68 cst_errmsg("damaged match string");
69 cst_error();
70 }
71 }
72 count += len;
73 }
74 }
75 if (out && dst - out + 1 < (int)max)
76 *dst++ = '\0';
77
78 return count;
79 }