revise typo
[libcext.git] / asprintf.h
1 /* https://git.datadissipation.net */
2 #ifndef ASPRINTF_H_
3 #define ASPRINTF_H_ 1
4
5 #ifdef ASPRINTF_INCLUDE_LIBC_
6 #include <stdarg.h>
7 #include <stdio.h>
8 #include <stdlib.h>
9 #endif
10
11 #ifndef HAVE_ASPRINTF
12 int vasprintf_(char **strp, const char *fmt, va_list ap);
13 int asprintf_(char **strp, const char *fmt, ...);
14 /*
15 * Credit for a big part of the macro madness:
16 * Jens Gustedt
17 * https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments/
18 */
19 #define vasprintf(s, f, a) vasprintf_(s, f, a)
20 #define I_COND_COMMA_(...) ,
21 #define I_PICK_ARG_(_1, _2, ARG, ...) ARG
22 #define I_HAS_COMMA_(...) I_PICK_ARG_(__VA_ARGS__, 1, 0)
23
24 #define I_ISEMPTY_(...) \
25 II_ISEMPTY_( \
26 /* test if there is just one argument, eventually an empty \
27 one */ \
28 I_HAS_COMMA_(__VA_ARGS__), \
29 /* test if I_COND_COMMA_ together with the argument \
30 adds a comma */ \
31 I_HAS_COMMA_(I_COND_COMMA_ __VA_ARGS__), \
32 /* test if the argument together with a parenthesis \
33 adds a comma */ \
34 I_HAS_COMMA_(__VA_ARGS__ (/*empty*/)), \
35 /* test if placing it between I_COND_COMMA_ and the \
36 parenthesis adds a comma */ \
37 I_HAS_COMMA_(I_COND_COMMA_ __VA_ARGS__ (/*empty*/)) \
38 )
39
40 #define I_PASTE5_(_0, _1, _2, _3, _4) _0 ## _1 ## _2 ## _3 ## _4
41 #define II_ISEMPTY_(_0, _1, _2, _3)\
42 I_HAS_COMMA_(I_PASTE5_(I_IS_EMPTY_CASE_, _0, _1, _2, _3))
43 #define I_IS_EMPTY_CASE_0001 ,
44
45 #define II_PASTE_(a) I_EMPTY_##a
46 #define I_PASTE_(a) II_PASTE_(a)
47
48 #define I_GET_ARG_(...) I_PICK_ARG_(__VA_ARGS__)
49 #define asprintf(s, f, ...)\
50 asprintf_(s, f I_PASTE_(I_ISEMPTY_(I_GET_ARG_(, , __VA_ARGS__))) __VA_ARGS__)
51 #define I_EMPTY_1
52 #define I_EMPTY_0 I_COND_COMMA_()
53 #endif
54
55 #ifdef ASPRINTF_IMPLEMENTATION_
56 int vasprintf_(char **strp, const char *fmt, va_list ap) {
57 int size, ret;
58 va_list tp;
59
60 va_copy(tp, ap);
61 size = vsnprintf(NULL, 0, fmt, tp);
62 va_end(tp);
63
64 if (size < 0) {
65 return -1;
66 }
67 *strp = malloc(size + 1);
68 if (*strp == NULL) {
69 return -1;
70 }
71
72 ret = vsnprintf(*strp, size + 1, fmt, ap);
73 if (ret < 0) {
74 free(*strp);
75 return -1;
76 }
77
78 return ret;
79 }
80
81 int asprintf_(char **strp, const char *fmt, ...) {
82 int ret;
83 va_list ap;
84
85 va_start(ap, fmt);
86 ret = vasprintf(strp, fmt, ap);
87 va_end(ap);
88
89 return ret;
90 }
91 #endif
92 #endif