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

inline static 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_free(struct vector *vec)
{
	free(vec->values);
	free(vec);
}