Restore sprintbuf(), add macro for string literals

Hawciz pointed out that the previous commit modifies the public
interface of printbuf. Per his suggestion, sprintbuf() was restored
and a new pair of macros was added that wraps printbuf_memappend().

Using a wrapper macro instead of modifying sprintbuf() also reduces
function call overhead, bringing total performance gains to
approximately 400%.
This commit is contained in:
Quentin Young
2017-02-03 21:43:59 +00:00
parent 9ff0f4987f
commit f6f852fd93
5 changed files with 157 additions and 43 deletions

View File

@@ -85,7 +85,6 @@ int printbuf_memappend(struct printbuf *p, const char *buf, int size)
if (printbuf_extend(p, p->bpos + size + 1) < 0)
return -1;
}
memcpy(p->buf + p->bpos, buf, size);
p->bpos += size;
p->buf[p->bpos]= '\0';
@@ -112,6 +111,34 @@ int printbuf_memset(struct printbuf *pb, int offset, int charvalue, int len)
return 0;
}
int sprintbuf(struct printbuf *p, const char *msg, ...)
{
va_list ap;
char *t;
int size;
char buf[128];
/* user stack buffer first */
va_start(ap, msg);
size = vsnprintf(buf, 128, msg, ap);
va_end(ap);
/* if string is greater than stack buffer, then use dynamic string
with vasprintf. Note: some implementation of vsnprintf return -1
if output is truncated whereas some return the number of bytes that
would have been written - this code handles both cases. */
if(size == -1 || size > 127) {
va_start(ap, msg);
if((size = vasprintf(&t, msg, ap)) < 0) { va_end(ap); return -1; }
va_end(ap);
printbuf_memappend(p, t, size);
free(t);
return size;
} else {
printbuf_memappend(p, buf, size);
return size;
}
}
void printbuf_reset(struct printbuf *p)
{
p->buf[0] = '\0';
@@ -125,8 +152,3 @@ void printbuf_free(struct printbuf *p)
free(p);
}
}
inline int sprintbuf(struct printbuf *p, const char *buf)
{
return printbuf_memappend(p, buf, strlen(buf));
}