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

static inline bool
vector_grow(struct vector *vec)
{
	vec->cap *= 2;
	vec->values = realloc(vec->values, sizeof(vec->values) * vec->cap);
	return vec->values != NULL;
}

struct vector *
vector_new_with_cap(size_t cap)
{
	struct vector *vec = malloc(sizeof(*vec));
	if (!vec) return NULL;
	vec->values = malloc(sizeof(vec->values) * cap);
	if (!vec->values) {
		free(vec);
		return NULL;
	}
	vec->cap = cap;
	vec->len = 0;

	return vec;
}

ssize_t
vector_push(struct vector *vec, void *val)
{
	if (vec->len >= vec->cap && !vector_grow(vec)) return -1;
	vec->values[vec->len] = val;
	vec->len++;

	return vec->len - 1;
}

void *
vector_pop(struct vector *vec)
{
	if (vec->len == 0) return NULL;
	return vec->values[--vec->len];
}

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