Rearranged whitespace (and comments) in all the code!
[mmh] / sbr / brkstring.c
1 /*
2  * brkstring.c -- (destructively) split a string into
3  *             -- an array of substrings
4  *
5  * This code is Copyright (c) 2002, by the authors of nmh.  See the
6  * COPYRIGHT file in the root directory of the nmh distribution for
7  * complete copyright information.
8  */
9
10 #include <h/mh.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 = (char **) 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                 return broken;
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;  /* NOT REACHED */
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         char *s;
84
85         if (str) {
86         for (s = str; *s; s++)
87                 if (c == *s)
88                 return 1;
89         }
90         return 0;
91 }