This avoids to call vsnprintf() twice in the common case where the
result is small.
The running time of a simple test case that called this function in
a loop improved from 13s to 8s due to this change.
__printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
{
int ret;
__printf_2_0 unsigned xvasprintf(char **result, const char *fmt, va_list ap)
{
int ret;
+ *result = para_malloc(size + 1);
- ret = vsnprintf(NULL, 0, fmt, aq);
+ ret = vsnprintf(*result, size, fmt, aq);
va_end(aq);
assert(ret >= 0);
va_end(aq);
assert(ret >= 0);
+ if (ret < size) /* OK */
+ return ret;
- *result = para_malloc(size);
+ *result = para_realloc(*result, size);
va_copy(aq, ap);
ret = vsnprintf(*result, size, fmt, aq);
va_end(aq);
va_copy(aq, ap);
ret = vsnprintf(*result, size, fmt, aq);
va_end(aq);