Commit | Line | Data |
---|---|---|
a666cab8 JA |
1 | #include <string.h> |
2 | #include <stdlib.h> | |
3 | ||
4 | #include "output_buffer.h" | |
f6cbf8ac | 5 | #include "../minmax.h" |
a666cab8 JA |
6 | |
7 | #define BUF_INC 1024 | |
8 | ||
e250c0a9 | 9 | void buf_output_init(struct buf_output *out) |
a666cab8 | 10 | { |
e250c0a9 | 11 | out->max_buflen = 0; |
a666cab8 | 12 | out->buflen = 0; |
e250c0a9 | 13 | out->buf = NULL; |
a666cab8 JA |
14 | } |
15 | ||
16 | void buf_output_free(struct buf_output *out) | |
17 | { | |
18 | free(out->buf); | |
8dd0eca3 | 19 | buf_output_init(out); |
a666cab8 JA |
20 | } |
21 | ||
5768cc2b | 22 | size_t buf_output_add(struct buf_output *out, const char *buf, size_t len) |
a666cab8 | 23 | { |
f6cbf8ac JA |
24 | if (out->max_buflen - out->buflen < len) { |
25 | size_t need = len - (out->max_buflen - out->buflen); | |
e250c0a9 | 26 | size_t old_max = out->max_buflen; |
a666cab8 | 27 | |
f6cbf8ac JA |
28 | need = max((size_t) BUF_INC, need); |
29 | out->max_buflen += need; | |
5768cc2b | 30 | out->buf = realloc(out->buf, out->max_buflen); |
f6cbf8ac JA |
31 | |
32 | old_max = max(old_max, out->buflen + len); | |
33 | if (old_max + need > out->max_buflen) | |
34 | need = out->max_buflen - old_max; | |
35 | memset(&out->buf[old_max], 0, need); | |
a666cab8 JA |
36 | } |
37 | ||
38 | memcpy(&out->buf[out->buflen], buf, len); | |
39 | out->buflen += len; | |
5768cc2b | 40 | return len; |
a666cab8 | 41 | } |