aboutsummaryrefslogtreecommitdiff
path: root/src/std_gc/list.c
blob: 7c56d6486faf2cc6a1ac36336b2fdc842c5f26d9 (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
#include "../../include/std_gc/list.h"
#include "../../include/value.h"
#include <stdio.h>
#include <string.h>
#include <assert.h>
#ifdef DEBUG
#define GC_DEBUG
#endif
#include <gc.h>

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

static int tsl_list_ensure_capacity(TslList *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 <<= 1;
    }

    new_ptr = GC_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_list_append(TslList *self, const TslValue *data) {
    if(!tsl_list_ensure_capacity(self, self->size + sizeof(TslValue)))
        return 0;
    memcpy((char*)self->data + self->size, data, sizeof(TslValue));
    self->size += sizeof(TslValue);
    return 1;
}

int tsl_list_set_capacity_hint(TslList *self, size_t capacity) {
    return tsl_list_ensure_capacity(self, capacity);
}

TslValue* tsl_list_begin(TslList *self) {
    return self->data;
}

TslValue* tsl_list_end(TslList *self) {
    return (TslValue*)((char*)self->data + self->size);
}

TslValue* tsl_list_get(const TslList *self, double index) {
    /* TODO: Verify if overflow check is needed */
    intptr_t index_i = index;
    if(index_i >= 0 && index_i < (intptr_t)self->size / (intptr_t)sizeof(TslValue))
        return (TslValue*)self->data + index_i;
    return NULL;
}