/src/clib/deps/asprintf/asprintf.c
Line | Count | Source (jump to first uncovered line) |
1 | | |
2 | | /** |
3 | | * `asprintf.c' - asprintf |
4 | | * |
5 | | * copyright (c) 2014 joseph werle <joseph.werle@gmail.com> |
6 | | */ |
7 | | |
8 | | #ifndef HAVE_ASPRINTF |
9 | | |
10 | | #include <stdlib.h> |
11 | | #include <stdio.h> |
12 | | #include <stdarg.h> |
13 | | |
14 | | #include "asprintf.h" |
15 | | |
16 | | int |
17 | 0 | asprintf (char **str, const char *fmt, ...) { |
18 | 0 | int size = 0; |
19 | 0 | va_list args; |
20 | | |
21 | | // init variadic argumens |
22 | 0 | va_start(args, fmt); |
23 | | |
24 | | // format and get size |
25 | 0 | size = vasprintf(str, fmt, args); |
26 | | |
27 | | // toss args |
28 | 0 | va_end(args); |
29 | |
|
30 | 0 | return size; |
31 | 0 | } |
32 | | |
33 | | int |
34 | 0 | vasprintf (char **str, const char *fmt, va_list args) { |
35 | 0 | int size = 0; |
36 | 0 | va_list tmpa; |
37 | | |
38 | | // copy |
39 | 0 | va_copy(tmpa, args); |
40 | | |
41 | | // apply variadic arguments to |
42 | | // sprintf with format to get size |
43 | 0 | size = vsnprintf(NULL, size, fmt, tmpa); |
44 | | |
45 | | // toss args |
46 | 0 | va_end(tmpa); |
47 | | |
48 | | // return -1 to be compliant if |
49 | | // size is less than 0 |
50 | 0 | if (size < 0) { return -1; } |
51 | | |
52 | | // alloc with size plus 1 for `\0' |
53 | 0 | *str = (char *) malloc(size + 1); |
54 | | |
55 | | // return -1 to be compliant |
56 | | // if pointer is `NULL' |
57 | 0 | if (NULL == *str) { return -1; } |
58 | | |
59 | | // format string with original |
60 | | // variadic arguments and set new size |
61 | 0 | size = vsprintf(*str, fmt, args); |
62 | 0 | return size; |
63 | 0 | } |
64 | | |
65 | | #endif |