aboutsummaryrefslogtreecommitdiff
path: root/src/std/buffer.c
blob: 0936573b856e8e3ce8d6e6b8a2b0399b4aec42fc (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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include "../../include/std/buffer.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>

void tsl_buffer_init(TslBuffer *self) {
    self->data = NULL;
    self->size = 0;
    self->capacity = 0;
}

void tsl_buffer_deinit(TslBuffer *self) {
    free(self->data);
    self->data = NULL;
    self->size = 0;
    self->capacity = 0;
}

static int tsl_buffer_ensure_capacity(TslBuffer *self, size_t new_size) {
    void *new_ptr;
    size_t new_capacity = self->capacity;
    if(new_size <= self->capacity)
        return 1;

    if(new_capacity == 0)
        new_capacity = 8;
    
    while(new_capacity < new_size) {
        new_capacity += (new_capacity >> 1);
    }

    new_ptr = realloc(self->data, new_capacity);
    if(!new_ptr) {
        fprintf(stderr, "Error: buffer append failed. Reason: out of memory\n");
        return 0;
    }

    self->data = new_ptr;
    self->capacity = new_capacity;
    return 1;
}

int tsl_buffer_append(TslBuffer *self, const void *data, size_t size) {
    if(!tsl_buffer_ensure_capacity(self, self->size + size))
        return 0;
    memcpy((char*)self->data + self->size, data, size);
    self->size += size;
    return 1;
}

void* tsl_buffer_pop(TslBuffer *self, size_t size) {
    assert(self->size >= size);
    self->size -= size;
    return (char*)self->data + self->size;
}

void* tsl_buffer_begin(TslBuffer *self) {
    return self->data;
}

void* tsl_buffer_end(TslBuffer *self) {
    return (char*)self->data + self->size;
}

void tsl_buffer_move(TslBuffer *dst, TslBuffer *src) {
    dst->data = src->data;
    dst->size = src->size;
    dst->capacity = src->capacity;
    src->data = NULL;
    src->size = 0;
    src->capacity = 0;
}