1 | /* |
---|
2 | * Replacement for a missing asprintf and vasprintf. |
---|
3 | * |
---|
4 | * Provides the same functionality as the standard GNU library routines |
---|
5 | * asprintf and vasprintf for those platforms that don't have them. |
---|
6 | * |
---|
7 | * Written by Russ Allbery <rra@stanford.edu> |
---|
8 | * This work is hereby placed in the public domain by its author. |
---|
9 | */ |
---|
10 | |
---|
11 | #include <config.h> |
---|
12 | #include <portable/system.h> |
---|
13 | |
---|
14 | /* |
---|
15 | * If we're running the test suite, rename the functions to avoid conflicts |
---|
16 | * with the system versions. |
---|
17 | */ |
---|
18 | #if TESTING |
---|
19 | # define asprintf test_asprintf |
---|
20 | # define vasprintf test_vasprintf |
---|
21 | int test_asprintf(char **, const char *, ...); |
---|
22 | int test_vasprintf(char **, const char *, va_list); |
---|
23 | #endif |
---|
24 | |
---|
25 | int |
---|
26 | asprintf(char **strp, const char *fmt, ...) |
---|
27 | { |
---|
28 | va_list args; |
---|
29 | int status; |
---|
30 | |
---|
31 | va_start(args, fmt); |
---|
32 | status = vasprintf(strp, fmt, args); |
---|
33 | va_end(args); |
---|
34 | return status; |
---|
35 | } |
---|
36 | |
---|
37 | int |
---|
38 | vasprintf(char **strp, const char *fmt, va_list args) |
---|
39 | { |
---|
40 | va_list args_copy; |
---|
41 | int status, needed; |
---|
42 | |
---|
43 | va_copy(args_copy, args); |
---|
44 | needed = vsnprintf(NULL, 0, fmt, args_copy); |
---|
45 | va_end(args_copy); |
---|
46 | if (needed < 0) { |
---|
47 | *strp = NULL; |
---|
48 | return needed; |
---|
49 | } |
---|
50 | *strp = malloc(needed + 1); |
---|
51 | if (*strp == NULL) |
---|
52 | return -1; |
---|
53 | status = vsnprintf(*strp, needed + 1, fmt, args); |
---|
54 | if (status >= 0) |
---|
55 | return status; |
---|
56 | else { |
---|
57 | free(*strp); |
---|
58 | *strp = NULL; |
---|
59 | return status; |
---|
60 | } |
---|
61 | } |
---|