vis

a vi-like editor based on Plan 9's structural regular expressions

git clone https://9o.is/git/vis.git

commit 04269aa7e1b898f1bcbfb4399a5a199f33efd6f5
parent 72755a8bdb7b8a9972d4af9d4a7d1acf104830c2
Author: Marc André Tanner <mat@brain-dump.org>
Date:   Wed, 18 May 2016 00:18:12 +0200

buffer: implement buffer_{v,}printf functions

Diffstat:
Mbuffer.c | 23+++++++++++++++++++++++
Mbuffer.h | 3+++
2 files changed, 26 insertions(+), 0 deletions(-)

diff --git 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 @@ -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 */