aboutsummaryrefslogtreecommitdiff
path: root/src/vec.c
blob: 7fb314e674d1e3b6b05526c0f750300f30623fd4 (plain) (blame)
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
62
63
64
65
66
67
68
69
70
71
72
73
74
#include <stdlib.h>
#include <assert.h>
#include <string.h>

#include <qbt/vec.h>

struct vec vec_create(size_t ns)
{
	return (struct vec) {
		       .n = 0,
		       .s = 1,
		       .ns = ns,
		       .buf = malloc(ns),
	};
}

void vec_reset(struct vec *v)
{
	v->n = 0;
}

size_t vec_len(struct vec *v)
{
	return v->n;
}

void *vec_at(struct vec *v, size_t i)
{
	assert(i < v->n && "out of vector bounds");
	return v->buf + i * v->ns;
}

void *vec_pop(struct vec *v)
{
	assert(v->n && "attempting to pop empty vector");
	v->n--;
	return v->buf + v->n * v->ns;
}

void vec_append(struct vec *v, void *n)
{
	v->n++;
	if (v->n >= v->s) {
		v->s *= 2;
		v->buf = realloc(v->buf, v->s * v->ns);
	}

	void *p = vec_at(v, v->n - 1);
	memcpy(p, n, v->ns);
}

void vec_destroy(struct vec *v)
{
	free(v->buf);
}

void vec_insert(struct vec *v, void *n, size_t i)
{
	assert(i <= vec_len(v));
	if (i == vec_len(v))
		vec_append(v, n);

	v->n++;
	if (v->n >= v->s) {
		v->s *= 2;
		v->buf = realloc(v->buf, v->s * v->ns);
	}

	void *p = vec_at(v, i);
	size_t elems = v->n - i - 1;
	size_t bytes = elems * v->ns;
	memmove(p + v->ns, p, bytes);
	memcpy(p, n, v->ns);
}