]> git.ozlabs.org Git - ccan/blob - tools/split.c
f5d016a9c874bd5beae39a30f7bff40397a18e1f
[ccan] / tools / split.c
1 #include "tools.h"
2 #include "talloc/talloc.h"
3 #include <string.h>
4
5 /* This is a dumb one which copies.  We could mangle instead. */
6 char **split(const void *ctx, const char *text, const char *delims,
7              unsigned int *nump)
8 {
9         char **lines = NULL;
10         unsigned int max = 64, num = 0;
11
12         lines = talloc_array(ctx, char *, max+1);
13
14         while (*text != '\0') {
15                 unsigned int len = strcspn(text, delims);
16                 lines[num] = talloc_array(lines, char, len + 1);
17                 memcpy(lines[num], text, len);
18                 lines[num][len] = '\0';
19                 text += len;
20                 text += strspn(text, delims);
21                 if (++num == max)
22                         lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
23         }
24         lines[num] = NULL;
25         if (nump)
26                 *nump = num;
27         return lines;
28 }
29