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

#include <stdlib.h>
#include <stdbool.h>

static bool
vector_grow(struct vector *vec)
{
	vec->cap *= VECTOR_GROW_RATE;
	vec->values = realloc(vec->values, sizeof(*vec->values) * vec->cap);
	if (vec->values == NULL) {
		return false;
	}

	return true;
}

/* create a new vector of the given capacity */
struct vector *
vector_new(size_t cap)
{
    struct vector *vec = malloc(sizeof *vec);
    vec->size = 0;
    vec->cap = cap;
    vec->values = malloc(vec->cap * sizeof *vec->values);
    return vec;
}

/* push a new value to the end of the vector's memory */
size_t
vector_push(struct vector *vec, void *value)
{
    if (vec->size == vec->cap) vector_grow(vec);
    vec->values[vec->size++] = value;
    return vec->size - 1;
}

/* free vector related memory */
void
vector_free(struct vector *vec)
{
    free(vec->values);
    free(vec);
}