]> git.ozlabs.org Git - ccan/blob - ccan/string/string.c
display a-z index for module search and some fixes
[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, size_t *size)
52 {
53         int ret;
54         size_t max = 16384, s;
55         char *buffer;
56
57         if (!size)
58                 size = &s;
59         *size = 0;
60
61         buffer = talloc_array(ctx, char, max+1);
62         while ((ret = read(fd, buffer + *size, max - *size)) > 0) {
63                 *size += ret;
64                 if (*size == max)
65                         buffer = talloc_realloc(ctx, buffer, char, max*=2 + 1);
66         }
67         if (ret < 0) {
68                 talloc_free(buffer);
69                 buffer = NULL;
70         } else
71                 buffer[*size] = '\0';
72
73         return buffer;
74 }
75
76 void *grab_file(const void *ctx, const char *filename, size_t *size)
77 {
78         int fd;
79         char *buffer;
80
81         if (!filename)
82                 fd = dup(STDIN_FILENO);
83         else
84                 fd = open(filename, O_RDONLY, 0);
85
86         if (fd < 0)
87                 return NULL;
88
89         buffer = grab_fd(ctx, fd, size);
90         close_noerr(fd);
91         return buffer;
92 }