diff options
Diffstat (limited to 'src/bytearray.c')
| -rw-r--r-- | src/bytearray.c | 34 |
1 files changed, 28 insertions, 6 deletions
diff --git a/src/bytearray.c b/src/bytearray.c index 7d0549b..39fad5f 100644 --- a/src/bytearray.c +++ b/src/bytearray.c | |||
| @@ -29,6 +29,17 @@ bytearray_t *byte_array_new(size_t initial) | |||
| 29 | a->capacity = (initial > PAGE_SIZE) ? (initial+(PAGE_SIZE-1)) & (~(PAGE_SIZE-1)) : PAGE_SIZE; | 29 | a->capacity = (initial > PAGE_SIZE) ? (initial+(PAGE_SIZE-1)) & (~(PAGE_SIZE-1)) : PAGE_SIZE; |
| 30 | a->data = malloc(a->capacity); | 30 | a->data = malloc(a->capacity); |
| 31 | a->len = 0; | 31 | a->len = 0; |
| 32 | a->stream = NULL; | ||
| 33 | return a; | ||
| 34 | } | ||
| 35 | |||
| 36 | bytearray_t *byte_array_new_for_stream(FILE *stream) | ||
| 37 | { | ||
| 38 | bytearray_t *a = (bytearray_t*)malloc(sizeof(bytearray_t)); | ||
| 39 | a->capacity = (size_t)-1; | ||
| 40 | a->data = NULL; | ||
| 41 | a->len = 0; | ||
| 42 | a->stream = stream; | ||
| 32 | return a; | 43 | return a; |
| 33 | } | 44 | } |
| 34 | 45 | ||
| @@ -43,6 +54,9 @@ void byte_array_free(bytearray_t *ba) | |||
| 43 | 54 | ||
| 44 | void byte_array_grow(bytearray_t *ba, size_t amount) | 55 | void byte_array_grow(bytearray_t *ba, size_t amount) |
| 45 | { | 56 | { |
| 57 | if (ba->stream) { | ||
| 58 | return; | ||
| 59 | } | ||
| 46 | size_t increase = (amount > PAGE_SIZE) ? (amount+(PAGE_SIZE-1)) & (~(PAGE_SIZE-1)) : PAGE_SIZE; | 60 | size_t increase = (amount > PAGE_SIZE) ? (amount+(PAGE_SIZE-1)) & (~(PAGE_SIZE-1)) : PAGE_SIZE; |
| 47 | ba->data = realloc(ba->data, ba->capacity + increase); | 61 | ba->data = realloc(ba->data, ba->capacity + increase); |
| 48 | ba->capacity += increase; | 62 | ba->capacity += increase; |
| @@ -50,12 +64,20 @@ void byte_array_grow(bytearray_t *ba, size_t amount) | |||
| 50 | 64 | ||
| 51 | void byte_array_append(bytearray_t *ba, void *buf, size_t len) | 65 | void byte_array_append(bytearray_t *ba, void *buf, size_t len) |
| 52 | { | 66 | { |
| 53 | if (!ba || !ba->data || (len <= 0)) return; | 67 | if (!ba || (!ba->stream && !ba->data) || (len <= 0)) return; |
| 54 | size_t remaining = ba->capacity-ba->len; | 68 | if (ba->stream) { |
| 55 | if (len > remaining) { | 69 | if (fwrite(buf, 1, len, ba->stream) < len) { |
| 56 | size_t needed = len - remaining; | 70 | #if DEBUG |
| 57 | byte_array_grow(ba, needed); | 71 | fprintf(stderr, "ERROR: Failed to write to stream.\n"); |
| 72 | #endif | ||
| 73 | } | ||
| 74 | } else { | ||
| 75 | size_t remaining = ba->capacity-ba->len; | ||
| 76 | if (len > remaining) { | ||
| 77 | size_t needed = len - remaining; | ||
| 78 | byte_array_grow(ba, needed); | ||
| 79 | } | ||
| 80 | memcpy(((char*)ba->data) + ba->len, buf, len); | ||
| 58 | } | 81 | } |
| 59 | memcpy(((char*)ba->data) + ba->len, buf, len); | ||
| 60 | ba->len += len; | 82 | ba->len += len; |
| 61 | } | 83 | } |
