aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--buffer.c23
-rw-r--r--buffer.h3
2 files changed, 26 insertions, 0 deletions
diff --git a/buffer.c b/buffer.c
index 410a059..b3c05d6 100644
--- a/buffer.c
+++ b/buffer.c
@@ -1,5 +1,7 @@
#include <stdlib.h>
#include <string.h>
+#include <stdarg.h>
+#include <stdio.h>
#include "buffer.h"
#include "util.h"
@@ -94,6 +96,27 @@ bool buffer_prepend0(Buffer *buf, const char *data) {
return buffer_prepend(buf, data, strlen(data) + (buf->len == 0));
}
+bool buffer_printf(Buffer *buf, const char *fmt, ...) {
+ va_list ap;
+ va_start(ap, fmt);
+ bool ret = buffer_vprintf(buf, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+bool buffer_vprintf(Buffer *buf, const char *fmt, va_list ap) {
+ va_list ap_save;
+ va_copy(ap_save, ap);
+ int len = vsnprintf(NULL, 0, fmt, ap);
+ if (len == -1 || !buffer_grow(buf, len+1))
+ return false;
+ bool ret = vsnprintf(buf->data, len+1, fmt, ap_save) == len;
+ if (ret)
+ buf->len = len+1;
+ va_end(ap_save);
+ return ret;
+}
+
size_t buffer_length0(Buffer *buf) {
size_t len = buf->len;
if (len > 0 && buf->data[len-1] == '\0')
diff --git a/buffer.h b/buffer.h
index 6b44a53..d0ecd63 100644
--- a/buffer.h
+++ b/buffer.h
@@ -40,6 +40,9 @@ bool buffer_append0(Buffer*, const char *data);
bool buffer_prepend(Buffer*, const void *data, size_t len);
/* prepend NUL-terminated data */
bool buffer_prepend0(Buffer*, const char *data);
+
+bool buffer_printf(Buffer*, const char *fmt, ...);
+bool buffer_vprintf(Buffer*, const char *fmt, va_list);
/* return length of a buffer without trailing NUL byte */
size_t buffer_length0(Buffer*);
/* return length of a buffer including possible NUL byte */