mirror of
https://github.com/postgres/postgres.git
synced 2025-11-24 00:23:06 +03:00
Add use of asprintf()
Add asprintf(), pg_asprintf(), and psprintf() to simplify string allocation and composition. Replacement implementations taken from NetBSD. Reviewed-by: Álvaro Herrera <alvherre@2ndquadrant.com> Reviewed-by: Asif Naeem <anaeem.it@gmail.com>
This commit is contained in:
@@ -852,3 +852,52 @@ pnstrdup(const char *in, Size len)
|
||||
out[len] = '\0';
|
||||
return out;
|
||||
}
|
||||
|
||||
/*
|
||||
* asprintf()-like functions around palloc, adapted from
|
||||
* http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/pkgtools/libnbcompat/files/asprintf.c
|
||||
*/
|
||||
|
||||
char *
|
||||
psprintf(const char *format, ...)
|
||||
{
|
||||
va_list ap;
|
||||
char *retval;
|
||||
|
||||
va_start(ap, format);
|
||||
retval = pvsprintf(format, ap);
|
||||
va_end(ap);
|
||||
|
||||
return retval;
|
||||
}
|
||||
|
||||
char *
|
||||
pvsprintf(const char *format, va_list ap)
|
||||
{
|
||||
char *buf, *new_buf;
|
||||
size_t len;
|
||||
int retval;
|
||||
va_list ap2;
|
||||
|
||||
len = 128;
|
||||
buf = palloc(len);
|
||||
|
||||
va_copy(ap2, ap);
|
||||
retval = vsnprintf(buf, len, format, ap);
|
||||
Assert(retval >= 0);
|
||||
|
||||
if (retval < len)
|
||||
{
|
||||
new_buf = repalloc(buf, retval + 1);
|
||||
va_end(ap2);
|
||||
return new_buf;
|
||||
}
|
||||
|
||||
len = (size_t)retval + 1;
|
||||
pfree(buf);
|
||||
buf = palloc(len);
|
||||
retval = vsnprintf(buf, len, format, ap2);
|
||||
va_end(ap2);
|
||||
Assert(retval == len - 1);
|
||||
return buf;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user