Skip to content

Commit

Permalink
refactor
Browse files Browse the repository at this point in the history
  • Loading branch information
Stephen Mathieson committed Jan 5, 2015
1 parent e395ecc commit 07123e0
Showing 1 changed file with 22 additions and 12 deletions.
34 changes: 22 additions & 12 deletions buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}

/*
Expand Down

1 comment on commit 07123e0

@marcomorain
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice.

Please sign in to comment.