#include "lib/string/printf.h"
#include "lib/err/torerr.h"
#include "lib/cc/torint.h"
#include "lib/malloc/malloc.h"
#include <stdlib.h>
#include <stdio.h>
int
tor_snprintf(char *str, size_t size, const char *format, ...)
{
va_list ap;
int r;
va_start(ap,format);
r = tor_vsnprintf(str,size,format,ap);
va_end(ap);
return r;
}
int
tor_vsnprintf(char *str, size_t size, const char *format, va_list args)
{
int r;
if (size == 0)
return -1;
if (size > SIZE_T_CEILING)
return -1;
#ifdef _WIN32
r = _vsnprintf(str, size, format, args);
#else
r = vsnprintf(str, size, format, args);
#endif
str[size-1] = '\0';
if (r < 0 || r >= (ssize_t)size)
return -1;
return r;
}
int
tor_asprintf(char **strp, const char *fmt, ...)
{
int r;
va_list args;
va_start(args, fmt);
r = tor_vasprintf(strp, fmt, args);
va_end(args);
if (!*strp || r < 0) {
raw_assert_unreached_msg("Internal error in asprintf");
}
return r;
}
int
tor_vasprintf(char **strp, const char *fmt, va_list args)
{
char *strp_tmp=NULL;
#ifdef HAVE_VASPRINTF
int r = vasprintf(&strp_tmp, fmt, args);
if (r < 0)
*strp = NULL; else
*strp = strp_tmp;
return r;
#elif defined(HAVE__VSCPRINTF)
int len, r;
va_list tmp_args;
va_copy(tmp_args, args);
len = _vscprintf(fmt, tmp_args);
va_end(tmp_args);
if (len < 0) {
*strp = NULL;
return -1;
}
strp_tmp = tor_malloc((size_t)len + 1);
r = _vsnprintf(strp_tmp, (size_t)len+1, fmt, args);
if (r != len) {
tor_free(strp_tmp);
*strp = NULL;
return -1;
}
*strp = strp_tmp;
return len;
#else
char buf[128];
int len, r;
va_list tmp_args;
va_copy(tmp_args, args);
len = vsnprintf(buf, sizeof(buf), fmt, tmp_args);
va_end(tmp_args);
buf[sizeof(buf) - 1] = '\0';
if (len < 0) {
*strp = NULL;
return -1;
}
if (len < (int)sizeof(buf)) {
*strp = tor_strdup(buf);
return len;
}
strp_tmp = tor_malloc((size_t)len+1);
r = tor_vsnprintf(strp_tmp, (size_t)len+1, fmt, args);
if (r != len) {
tor_free(strp_tmp);
*strp = NULL;
return -1;
}
*strp = strp_tmp;
return len;
#endif
}