]> diplodocus.org Git - nmh/blob - sbr/brkstring.c
mhbuildsbr.c: Flip logic, moving goto to then-block; no need for else.
[nmh] / sbr / brkstring.c
1 /* brkstring.c -- (destructively) split a string into
2 * -- an array of substrings
3 *
4 * This code is Copyright (c) 2002, by the authors of nmh. See the
5 * COPYRIGHT file in the root directory of the nmh distribution for
6 * complete copyright information.
7 */
8
9 #include <h/mh.h>
10 #include <h/utils.h>
11
12 /* allocate this number of pointers at a time */
13 #define NUMBROKEN 256
14
15 static char **broken = NULL; /* array of substring start addresses */
16 static int len = 0; /* current size of "broken" */
17
18 /*
19 * static prototypes
20 */
21 static int brkany (char, char *);
22
23
24 char **
25 brkstring (char *str, char *brksep, char *brkterm)
26 {
27 int i;
28 char c, *s;
29
30 /* allocate initial space for pointers on first call */
31 if (!broken) {
32 len = NUMBROKEN;
33 broken = (char **) mh_xmalloc ((size_t) (len * sizeof(*broken)));
34 }
35
36 /*
37 * scan string, replacing separators with zeroes
38 * and enter start addresses in "broken".
39 */
40 s = str;
41
42 for (i = 0;; i++) {
43
44 /* enlarge pointer array, if necessary */
45 if (i >= len) {
46 len += NUMBROKEN;
47 broken = mh_xrealloc (broken, (size_t) (len * sizeof(*broken)));
48 }
49
50 while (brkany (c = *s, brksep))
51 *s++ = '\0';
52
53 /*
54 * we are either at the end of the string, or the
55 * terminator found has been found, so finish up.
56 */
57 if (!c || brkany (c, brkterm)) {
58 *s = '\0';
59 broken[i] = NULL;
60 break;
61 }
62
63 /* set next start addr */
64 broken[i] = s;
65
66 while ((c = *++s) && !brkany (c, brksep) && !brkany (c, brkterm))
67 ; /* empty body */
68 }
69
70 return broken;
71 }
72
73
74 /*
75 * If the character is in the string,
76 * return 1, else return 0.
77 */
78
79 static int
80 brkany (char c, char *str)
81 {
82 return str && c && strchr(str, c);
83 }