summaryrefslogtreecommitdiff
path: root/lib/vector.c
blob: 91c349b44a35067c414bb47bbc3c89d3b21a7d9f (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
#include <lib/vector.h>

#include <platform/osal.h>

#include <assert.h>
#include <string.h>

int vector_init(struct vector *v)
{
	assert(v != NULL);
	size_t initial = 50;
	v->size = 0;
	v->capacity = initial;
	v->buffer = mem_alloc(initial * sizeof(void*)); // add safety
	if (v->buffer == NULL)
		return -1;
	return 0;
}

int vector_free(struct vector *v)
{
	assert(v != NULL);
	mem_free((void*)v->buffer);
}

int vector_reserve(struct vector *v, size_t nc)
{
	assert(v != NULL);
	void *nb = mem_alloc((nc) * sizeof(void*));

	if (nb == NULL) 
		return -1;

	memcpy(nb, v->buffer, v->size * sizeof(void*));
	v->capacity = nc;

	if (v->buffer == NULL) 
		return -1;
	
	mem_free(v->buffer);
	v->buffer = nb;
	return 0;
}

int vector_emplace_back(struct vector *v, void *p)
{
	assert(v != NULL);

	if (p == NULL) 
		return -1;

	if (v->size >= v->capacity)
		if (vector_reserve(v, v->capacity * 2) == -1) 
			return -1;


	v->buffer[v->size] = p;
	v->size++;	
	
	return 0;
}