summaryrefslogtreecommitdiffstats
path: root/vec.c
blob: 719344eaea75ffccf6f1b01b1702891a48d3ad6f (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
#include <string.h>

#include "mem.h"
#include "vec.h"

#define DEFAULT_LEN 8

void vec_init(struct vec *v, size_t unit_size)
{
	v->data = NULL;
	v->len = 0;
	v->cap = 0;
	v->unit_size = unit_size;
}

void vec_push(struct vec *v, const void *item)
{
	void *target;

	if (v->len == v->cap) {
		v->cap = (v->cap == 0) ? DEFAULT_LEN : v->cap * 2;
		v->data = REALLOC(v->data, v->cap * v->unit_size);
	}

	target = (char *)v->data + (v->len * v->unit_size);
	memcpy(target, item, v->unit_size);
	v->len++;
}

void *vec_pop(struct vec *v)
{
	if (v->len == 0) 
		return NULL;
	v->len--;
	return (char *)v->data + (v->len * v->unit_size);
}

void *vec_top(struct vec *v)
{
	if (v->len == 0) 
		return NULL;
	return (char *)v->data + ((v->len - 1) * v->unit_size);
}

void vec_free(struct vec *v)
{
	free(v->data);
	v->data = NULL;
	v->len = v->cap = 0;
}