aboutsummaryrefslogtreecommitdiff
path: root/vector.inc.h
blob: 2b23eadcc9415a90d835abc50ea0721656a96042 (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
#ifndef TYPE
#error "Set TYPE before including self file"
#else

#include "macro.h"
#include "err.h"

INIT_F(VECT(TYPE)) {
	self->length = 0;
	self->alloc = 1;
	self->items = (TYPE**) calloc(sizeof(*self->items), self->alloc);
	return 0;
}

FREE_F(VECT(TYPE)) {
	for (unsigned int i = 0; i < self->length; i++) {
		FFREE(TYPE, self->items[i]);
	}
	free(self->items);
	return 0;
}

int PUSH(VECT(TYPE))(VECT(TYPE)* self, TYPE* t) {
	if (self->length + 1 > self->alloc) {
		self->alloc <<= 1;
		self->items = (TYPE**) realloc(self->items, sizeof(*self->items) * self->alloc);
	}

	self->items[self->length] = t;
	++self->length;
	return 0;
}

TYPE* GET(VECT(TYPE))(VECT(TYPE)* self, unsigned int idx) {
	if (idx >= self->length) {
		ERR("Index out of range"); 
		return NULL;
	}

	return self->items[idx];
}

int EMPTY(VECT(TYPE))(VECT(TYPE)* self) {
	return self->length == 0;
}

unsigned int SIZE(VECT(TYPE))(VECT(TYPE)* self) {
	return self->length;
}

#endif /* TYPE */