aboutsummaryrefslogtreecommitdiff
path: root/src/vector.c
blob: 40dc92c624aa6e4d9bc202b0a8eea639725ee6a4 (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
#include "vector.h"
#include <stdlib.h>

static void vector_resize(Vector *v, size_t new_capacity);

Vector *vector_new(void) {
    Vector *v = (Vector *)malloc(sizeof(Vector));
    if (!v)
        return NULL;

    v->data = (void **)malloc(VECTOR_INITIAL_CAPACITY * sizeof(void *));
    if (!v->data) {
        free(v);
        return NULL;
    }

    v->size = 0;
    v->capacity = VECTOR_INITIAL_CAPACITY;
    return v;
}

void vector_delete(Vector *v) {
    free(v->data);
    free(v);
}

void vector_push(Vector *v, void *element) {
    if (v->size >= v->capacity)
        vector_resize(v, v->capacity * VECTOR_GROWTH_FACTOR);
    v->data[v->size++] = element;
}

void *vector_pop(Vector *v) {
    if (!v->size) return NULL;
    return v->data[--v->size];
}

void *vector_get(Vector *v, size_t index) {
    if (index >= v->size)
        return NULL;
    return v->data[index];
} 

void vector_set(Vector *v, size_t index, void *element) {
    if (index >= v->size)
        return;
    v->data[index] = element;
}

size_t vector_size(Vector *v) {
    return v->size;
}

int vector_is_empty(Vector *v) {
    return v->size == 0;
}

void vector_clear(Vector *v) {
    v->size = 0;
}

static void vector_resize(Vector *v, size_t new_capacity) {
    void **new_data = (void **)realloc(v->data, new_capacity * sizeof(void *));
    if (new_data) {
        v->data = new_data;
        v->capacity = new_capacity;
    }
}