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" | |
7 | ||
8 | #define BUF_INC 1024 | |
9 | ||
10 | void buf_output_init(struct buf_output *out, int index) | |
11 | { | |
12 | out->max_buflen = BUF_INC; | |
13 | out->buf = malloc(out->max_buflen); | |
14 | memset(out->buf, 0, out->max_buflen); | |
15 | out->buflen = 0; | |
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 JA |
24 | { |
25 | while (out->max_buflen - out->buflen < len) { | |
26 | size_t newlen = out->max_buflen + BUF_INC - out->buflen; | |
27 | ||
a666cab8 | 28 | out->max_buflen += BUF_INC; |
5768cc2b | 29 | out->buf = realloc(out->buf, out->max_buflen); |
a666cab8 JA |
30 | memset(&out->buf[out->buflen], 0, newlen); |
31 | } | |
32 | ||
33 | memcpy(&out->buf[out->buflen], buf, len); | |
34 | out->buflen += len; | |
5768cc2b | 35 | return len; |
a666cab8 JA |
36 | } |
37 | ||
5768cc2b | 38 | size_t buf_output_flush(struct buf_output *out) |
a666cab8 | 39 | { |
5768cc2b JA |
40 | size_t ret = 0; |
41 | ||
a666cab8 | 42 | if (out->buflen) { |
5768cc2b | 43 | ret = log_local_buf(out->buf, out->buflen); |
a666cab8 JA |
44 | memset(out->buf, 0, out->max_buflen); |
45 | out->buflen = 0; | |
46 | } | |
5768cc2b JA |
47 | |
48 | return ret; | |
a666cab8 | 49 | } |