]> git.ozlabs.org Git - ccan/blob - ccan/string/string.c
merge
[ccan] / ccan / string / string.c
1 #include <unistd.h>
2 #include <stdint.h>
3 #include <string.h>
4 #include <limits.h>
5 #include <assert.h>
6 #include <stdlib.h>
7 #include "string.h"
8 #include "talloc/talloc.h"
9 #include <sys/types.h>
10 #include <sys/stat.h>
11 #include <fcntl.h>
12 #include <errno.h>
13 #include "noerr/noerr.h"
14
15 char **strsplit(const void *ctx, const char *string, const char *delims,
16                  unsigned int *nump)
17 {
18         char **lines = NULL;
19         unsigned int max = 64, num = 0;
20
21         lines = talloc_array(ctx, char *, max+1);
22
23         while (*string != '\0') {
24                 unsigned int len = strcspn(string, delims);
25                 lines[num] = talloc_array(lines, char, len + 1);
26                 memcpy(lines[num], string, len);
27                 lines[num][len] = '\0';
28                 string += len;
29                 string += strspn(string, delims) ? 1 : 0;
30                 if (++num == max)
31                         lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
32         }
33         lines[num] = NULL;
34         if (nump)
35                 *nump = num;
36         return lines;
37 }
38
39 char *strjoin(const void *ctx, char *strings[], const char *delim)
40 {
41         unsigned int i;
42         char *ret = talloc_strdup(ctx, "");
43
44         for (i = 0; strings[i]; i++) {
45                 ret = talloc_append_string(ret, strings[i]);
46                 ret = talloc_append_string(ret, delim);
47         }
48         return ret;
49 }
50
51 void *grab_fd(const void *ctx, int fd)
52 {
53         int ret;
54         unsigned int max = 16384, size = 0;
55         char *buffer;
56
57         buffer = talloc_array(ctx, char, max+1);
58         while ((ret = read(fd, buffer + size, max - size)) > 0) {
59                 size += ret;
60                 if (size == max)
61                         buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
62         }
63         if (ret < 0) {
64                 talloc_free(buffer);
65                 buffer = NULL;
66         } else
67                 buffer[size] = '\0';
68
69         return buffer;
70 }
71
72 void *grab_file(const void *ctx, const char *filename)
73 {
74         int fd;
75         char *buffer;
76
77         if (streq(filename, "-"))
78                 fd = dup(STDIN_FILENO);
79         else
80                 fd = open(filename, O_RDONLY, 0);
81
82         if (fd < 0)
83                 return NULL;
84
85         buffer = grab_fd(ctx, fd);
86         close_noerr(fd);
87         return buffer;
88 }