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