1 /* https://git.datadissipation.net */
5 #ifdef ASPRINTF_INCLUDE_LIBC_
12 int vasprintf_(char **strp
, const char *fmt
, va_list ap
);
13 int asprintf_(char **strp
, const char *fmt
, ...);
15 * Credit for a big part of the macro madness:
17 * https://gustedt.wordpress.com/2010/06/08/detect-empty-macro-arguments/
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)
24 #define I_ISEMPTY_(...) \
26 /* test if there is just one argument, eventually an empty \
28 I_HAS_COMMA_(__VA_ARGS__), \
29 /* test if I_COND_COMMA_ together with the argument \
31 I_HAS_COMMA_(I_COND_COMMA_ __VA_ARGS__), \
32 /* test if the argument together with a parenthesis \
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*/)) \
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 ,
45 #define II_PASTE_(a) I_EMPTY_##a
46 #define I_PASTE_(a) II_PASTE_(a)
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__)
52 #define I_EMPTY_0 I_COND_COMMA_()
55 #ifdef ASPRINTF_IMPLEMENTATION_
56 int vasprintf_(char **strp
, const char *fmt
, va_list ap
) {
61 size
= vsnprintf(NULL
, 0, fmt
, tp
);
67 *strp
= malloc(size
+ 1);
72 ret
= vsnprintf(*strp
, size
+ 1, fmt
, ap
);
81 int asprintf_(char **strp
, const char *fmt
, ...) {
86 ret
= vasprintf(strp
, fmt
, ap
);