diff --git a/buffer.c b/buffer.c index be0b08d..e9bdbb7 100644 --- a/buffer.c +++ b/buffer.c @@ -143,29 +143,39 @@ buffer_resize(buffer_t *self, size_t n) { /* * Append a printf-style formatted string to the buffer. */ + int buffer_appendf(buffer_t *self, const char *format, ...) { va_list ap; + va_list tmpa; + char *dst = NULL; + int length = 0; + int required = 0; + int bytes = 0; + va_start(ap, format); - const int initial_len = buffer_length(self); - // First, we compute how many bytes are needed for the formatted string - // and allocate that much more space in the buffer. - va_list tmpa; + length = buffer_length(self); + + // First, we compute how many bytes are needed + // for the formatted string and allocate that + // much more space in the buffer. va_copy(tmpa, ap); - const int space_required = vsnprintf(NULL, 0, format, tmpa); + required = vsnprintf(NULL, 0, format, tmpa); va_end(tmpa); - const int resized = buffer_resize(self, initial_len + space_required); - if (resized == -1) { + if (-1 == buffer_resize(self, length + required)) { va_end(ap); return -1; } - // Next format the string into the space that we have made room for. - char* dst = self->data + initial_len; - const int bytes_formatted = vsnprintf(dst, 1+space_required, format, ap); - + // Next format the string into the space that we + // have made room for. + dst = self->data + length; + bytes = vsnprintf(dst, 1 + required, format, ap); va_end(ap); - return (bytes_formatted < 0) ? -1 : 0; + + return bytes < 0 + ? -1 + : 0; } /*