diff options
| author | Marc André Tanner <mat@brain-dump.org> | 2016-05-18 00:18:12 +0200 |
|---|---|---|
| committer | Marc André Tanner <mat@brain-dump.org> | 2016-05-18 15:07:02 +0200 |
| commit | ffe11d4cd4a4c81395b3272706cf696b93710c61 (patch) | |
| tree | cd0d2e5991774ee57ba5012d2f09bfe81022c529 | |
| parent | 826be3072ad3ce475ea39d80e5a6606a896d98c2 (diff) | |
| download | vis-ffe11d4cd4a4c81395b3272706cf696b93710c61.tar.gz vis-ffe11d4cd4a4c81395b3272706cf696b93710c61.tar.xz | |
buffer: implement buffer_{v,}printf functions
| -rw-r--r-- | buffer.c | 23 | ||||
| -rw-r--r-- | buffer.h | 3 |
2 files changed, 26 insertions, 0 deletions
@@ -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') @@ -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 */ |
