]> git.ozlabs.org Git - ccan/blob - ccan/stringbuilder/stringbuilder.c
base64: fix for unsigned chars (e.g. ARM).
[ccan] / ccan / stringbuilder / stringbuilder.c
1 /* CC0 (Public domain) - see LICENSE file for details */
2 #include <ccan/stringbuilder/stringbuilder.h>
3 #include <string.h>
4 #include <errno.h>
5
6 int stringbuilder_args(char* str, size_t str_sz, const char* delim, ...)
7 {
8         int res;
9         va_list ap;
10         va_start(ap, delim);
11         res = stringbuilder_va(str, str_sz, delim, ap);
12         va_end(ap);
13         return res;
14 }
15
16 static int stringbuilder_cpy(
17                 char** str, size_t* str_sz, const char* s, size_t s_len)
18 {
19         if (!s)
20                 return 0;
21
22         if (*str != s) {
23                 if (!s_len)
24                         s_len = strlen(s);
25                 /* Include nul term! */
26                 if (s_len >= *str_sz)
27                         return EMSGSIZE;
28                 strcpy(*str, s);
29         }
30         *str += s_len;
31         *str_sz -= s_len;
32         return 0;
33 }
34
35 int stringbuilder_va(char* str, size_t str_sz, const char* delim, va_list ap)
36 {
37         int res = 0;
38         size_t delim_len = 0;
39         const char* s = va_arg(ap, const char*);
40
41         if (delim)
42                 delim_len = strlen(delim);
43
44         res = stringbuilder_cpy(&str, &str_sz, s, 0);
45         s = va_arg(ap, const char*);
46         while(s && !res) {
47                 res = stringbuilder_cpy(&str, &str_sz,
48                                 delim, delim_len);
49                 if (!res) {
50                         res = stringbuilder_cpy(&str, &str_sz,
51                                                 s, 0);
52                         s = va_arg(ap, const char*);
53                 }
54         }
55         return res;
56 }
57
58 int stringbuilder_array(char* str, size_t str_sz, const char* delim,
59                 size_t n_strings, const char** strings)
60 {
61         int res = 0;
62         size_t delim_len = 0;
63
64         if (delim)
65                 delim_len = strlen(delim);
66
67         res = stringbuilder_cpy(&str, &str_sz,
68                         *(strings++), 0);
69         while(--n_strings && !res) {
70                 res = stringbuilder_cpy(&str, &str_sz,
71                                 delim, delim_len);
72                 if (!res)
73                         res = stringbuilder_cpy(&str, &str_sz,
74                                         *(strings++), 0);
75         }
76         return res;
77
78 }