Merge commit 'junio/next' into next
[git/platforms/storm.git] / compat / snprintf.c
blobbddfa5cdde245bfa20353b0076446d7b5d5ab35b
1 #include "../git-compat-util.h"
3 /*
4 * The size parameter specifies the available space, i.e. includes
5 * the trailing NUL byte; but Windows's vsnprintf expects the
6 * number of characters to write without the trailing NUL.
7 */
8 #ifndef SNPRINTF_SIZE_CORR
9 #define SNPRINTF_SIZE_CORR 0
10 #endif
12 #undef vsnprintf
13 int git_vsnprintf(char *str, size_t maxsize, const char *format, va_list ap)
15 char *s;
16 int ret;
18 ret = vsnprintf(str, maxsize-SNPRINTF_SIZE_CORR, format, ap);
19 if (ret != -1) {
20 /* Windows does not NUL-terminate if result fits exactly */
21 str[ret] = 0;
22 return ret;
25 s = NULL;
26 if (maxsize < 128)
27 maxsize = 128;
29 while (ret == -1) {
30 maxsize *= 4;
31 str = realloc(s, maxsize);
32 if (! str)
33 break;
34 s = str;
35 ret = vsnprintf(str, maxsize-SNPRINTF_SIZE_CORR, format, ap);
37 free(s);
38 return ret;
41 int git_snprintf(char *str, size_t maxsize, const char *format, ...)
43 va_list ap;
44 int ret;
46 va_start(ap, format);
47 ret = git_vsnprintf(str, maxsize, format, ap);
48 va_end(ap);
50 return ret;