1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
|
/* split.c -- split strings based on separators ($Revision: 1.1.1.1 $) */
#include "es.h"
#include "gc.h"
static Boolean coalesce;
static Boolean splitchars;
static Buffer *buffer;
static List *value;
static Boolean ifsvalid = FALSE;
static char ifs[10], isifs[256];
extern void startsplit(const char *sep, Boolean coalescef) {
static Boolean initialized = FALSE;
if (!initialized) {
initialized = TRUE;
globalroot(&value);
}
value = NULL;
buffer = NULL;
coalesce = coalescef;
splitchars = !coalesce && *sep == '\0';
if (!ifsvalid || !streq(sep, ifs)) {
int c;
if (strlen(sep) + 1 < sizeof ifs) {
strcpy(ifs, sep);
ifsvalid = TRUE;
} else
ifsvalid = FALSE;
memzero(isifs, sizeof isifs);
for (isifs['\0'] = TRUE; (c = (*(unsigned const char *)sep)) != '\0'; sep++)
isifs[c] = TRUE;
}
}
extern void splitstring(char *in, size_t len, Boolean endword) {
Buffer *buf = buffer;
unsigned char *s = (unsigned char *) in, *inend = s + len;
if (splitchars) {
assert(buf == NULL);
while (s < inend) {
Term *term = mkstr(gcndup((char *) s++, 1));
value = mklist(term, value);
}
return;
}
if (!coalesce && buf == NULL)
buf = openbuffer(0);
while (s < inend) {
int c = *s++;
if (buf != NULL)
if (isifs[c]) {
Term *term = mkstr(sealcountedbuffer(buf));
value = mklist(term, value);
buf = coalesce ? NULL : openbuffer(0);
} else
buf = bufputc(buf, c);
else if (!isifs[c])
buf = bufputc(openbuffer(0), c);
}
if (endword && buf != NULL) {
Term *term = mkstr(sealcountedbuffer(buf));
value = mklist(term, value);
buf = NULL;
}
buffer = buf;
}
extern List *endsplit(void) {
List *result;
if (buffer != NULL) {
Term *term = mkstr(sealcountedbuffer(buffer));
value = mklist(term, value);
buffer = NULL;
}
result = reverse(value);
value = NULL;
return result;
}
extern List *fsplit(const char *sep, List *list, Boolean coalesce) {
Ref(List *, lp, list);
startsplit(sep, coalesce);
for (; lp != NULL; lp = lp->next) {
char *s = getstr(lp->term);
splitstring(s, strlen(s), TRUE);
}
RefEnd(lp);
return endsplit();
}
|