libsa: add asprintf()

asprintf() is a nice tool for string processing.

MFC after:	2 weeks
This commit is contained in:
Toomas Soome 2019-01-17 22:00:02 +00:00
parent 7c52f914db
commit 5e84b57828
2 changed files with 29 additions and 0 deletions

View File

@ -121,6 +121,34 @@ snprint_func(int ch, void *arg)
pbuf->size--;
}
int
asprintf(char **buf, const char *cfmt, ...)
{
int retval;
struct print_buf arg;
va_list ap;
*buf = NULL;
va_start(ap, cfmt);
retval = kvprintf(cfmt, NULL, NULL, 10, ap);
va_end(ap);
if (retval <= 0)
return (-1);
arg.size = retval + 1;
arg.buf = *buf = malloc(arg.size);
if (*buf == NULL)
return (-1);
va_start(ap, cfmt);
retval = kvprintf(cfmt, &snprint_func, &arg, 10, ap);
va_end(ap);
if (arg.size >= 1)
*(arg.buf)++ = 0;
return (retval);
}
int
snprintf(char *buf, size_t size, const char *cfmt, ...)
{

View File

@ -268,6 +268,7 @@ extern void *reallocf(void *ptr, size_t size);
extern void mallocstats(void);
extern int printf(const char *fmt, ...) __printflike(1, 2);
extern int asprintf(char **buf, const char *cfmt, ...) __printflike(2, 3);
extern int sprintf(char *buf, const char *cfmt, ...) __printflike(2, 3);
extern int snprintf(char *buf, size_t size, const char *cfmt, ...) __printflike(3, 4);
extern int vprintf(const char *fmt, __va_list);