]> git.ozlabs.org Git - ccan/blob - ccan/string/string.c
9182ac0650fb7b9c94ba72aa12872ca7f44310d0
[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
14 char **strsplit(const void *ctx, const char *string, const char *delims,
15                  unsigned int *nump)
16 {
17         char **lines = NULL;
18         unsigned int max = 64, num = 0;
19
20         lines = talloc_array(ctx, char *, max+1);
21
22         while (*string != '\0') {
23                 unsigned int len = strcspn(string, delims);
24                 lines[num] = talloc_array(lines, char, len + 1);
25                 memcpy(lines[num], string, len);
26                 lines[num][len] = '\0';
27                 string += len;
28                 string += strspn(string, delims) ? 1 : 0;
29                 if (++num == max)
30                         lines = talloc_realloc(ctx, lines, char *, max*=2 + 1);
31         }
32         lines[num] = NULL;
33         if (nump)
34                 *nump = num;
35         return lines;
36 }
37
38 char *strjoin(const void *ctx, char *strings[], const char *delim)
39 {
40         unsigned int i;
41         char *ret = talloc_strdup(ctx, "");
42
43         for (i = 0; strings[i]; i++) {
44                 ret = talloc_append_string(ret, strings[i]);
45                 ret = talloc_append_string(ret, delim);
46         }
47         return ret;
48 }
49
50 static int close_no_errno(int fd)
51 {
52         int ret = 0, serrno = errno;
53         if (close(fd) < 0)
54                 ret = errno;
55         errno = serrno;
56         return ret;
57 }
58
59 void *grab_fd(const void *ctx, int fd)
60 {
61         int ret;
62         unsigned int max = 16384, size = 0;
63         char *buffer;
64
65         buffer = talloc_array(ctx, char, max+1);
66         while ((ret = read(fd, buffer + size, max - size)) > 0) {
67                 size += ret;
68                 if (size == max)
69                         buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
70         }
71         if (ret < 0) {
72                 talloc_free(buffer);
73                 buffer = NULL;
74         } else
75                 buffer[size] = '\0';
76
77         return buffer;
78 }
79
80 void *grab_file(const void *ctx, const char *filename)
81 {
82         int fd;
83         char *buffer;
84
85         if (streq(filename, "-"))
86                 fd = dup(STDIN_FILENO);
87         else
88                 fd = open(filename, O_RDONLY, 0);
89
90         if (fd < 0)
91                 return NULL;
92
93         buffer = grab_fd(ctx, fd);
94         close_no_errno(fd);
95         return buffer;
96 }