Skip to content

Commit

Permalink
output_buffer: only realloc once, and memset just what we need
Browse files Browse the repository at this point in the history
No need looping around a realloc(), just alloc what we need upfront.
Additionally, don't memset the parts we'll be copying into anyway.

Signed-off-by: Jens Axboe <[email protected]>
  • Loading branch information
axboe committed Oct 31, 2015
1 parent 125451c commit f6cbf8a
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions lib/output_buffer.c
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@

#include "output_buffer.h"
#include "../log.h"
#include "../minmax.h"

#define BUF_INC 1024

Expand All @@ -21,12 +22,18 @@ void buf_output_free(struct buf_output *out)

size_t buf_output_add(struct buf_output *out, const char *buf, size_t len)
{
while (out->max_buflen - out->buflen < len) {
if (out->max_buflen - out->buflen < len) {
size_t need = len - (out->max_buflen - out->buflen);
size_t old_max = out->max_buflen;

out->max_buflen += BUF_INC;
need = max((size_t) BUF_INC, need);
out->max_buflen += need;
out->buf = realloc(out->buf, out->max_buflen);
memset(&out->buf[old_max], 0, BUF_INC);

old_max = max(old_max, out->buflen + len);
if (old_max + need > out->max_buflen)
need = out->max_buflen - old_max;
memset(&out->buf[old_max], 0, need);
}

memcpy(&out->buf[out->buflen], buf, len);
Expand Down

0 comments on commit f6cbf8a

Please sign in to comment.