summaryrefslogtreecommitdiff
path: root/src/buffer.c
blob: a3ee649aa2e58873d58741cdb2cf3ee26f992f56 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "buffer.h"
#include <string.h>
#include <malloc.h>
#include <assert.h>

void init_growable_buffer(growable_buffer *buffer) {
    buffer->size = GROW_SIZE;
    buffer->used = 0;
    buffer->content = malloc(GROW_SIZE);
    assert( buffer->content != 0 );
}

char* grow_growable_buffer(growable_buffer *buffer, size_t at_least) {
    size_t new_size = ((at_least % GROW_SIZE) + 1 ) * GROW_SIZE;
    if (new_size < buffer->size){
        buffer->content = realloc(buffer->content, new_size);
        buffer->size = new_size;
    }
    return buffer->content;
}

void append_growable_buffer(growable_buffer *buffer, char* content,
        size_t length) {
    size_t i;
    char *buf;

    if (buffer->size <= buffer->used + length) {
        buf = grow_growable_buffer(buffer, length);
    } else {
        buf = buffer->content;
    }

    for (i=0; i<length; i++){
        buf[buffer->used + i] = content[i];
    }
}

void free_growable_buffer(growable_buffer *buffer) {
    free(buffer->content);
    buffer->content = NULL;
    buffer->used = 0;
    buffer->size = 0;
}



void init_fixed_buffer(fixed_buffer *buffer, char *orig) {
    buffer->content = orig;
    buffer->size = strlen(orig);
    assert( buffer->content != NULL );
}