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