-
Notifications
You must be signed in to change notification settings - Fork 0
/
vec.h
98 lines (83 loc) · 1.64 KB
/
vec.h
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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#if !defined(con_t) || !defined(val_t)
#error "Define con_t and val_t before including"
#endif
/* preprocessor magic */
#define Ccat3(a,b) a##_##b
#define Ccat2(a,b) Ccat3(a,b)
#define Cpref(x) Ccat2(con_t,x)
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#include <stddef.h>
typedef struct
{
size_t length;
size_t alloc;
val_t *data;
} con_t;
con_t Cpref(init)(void)
{
con_t v;
v.length = 0;
v.alloc = 0;
v.data = NULL;
return v;
}
void Cpref(grow)(con_t *v, size_t n)
{
if (v->length + n >= v->alloc)
{
v->alloc = v->alloc ? v->alloc * 2 : 32;
if (v->alloc < v->length + n)
v->alloc = v->length + n;
v->data = (val_t*)realloc(v->data, sizeof(v->data[0]) * v->alloc);
}
}
void Cpref(push)(con_t *v, val_t x)
{
Cpref(grow)(v, 1);
v->data[v->length++] = x;
}
val_t Cpref(top)(con_t *v)
{
assert(v->length);
return v->data[v->length - 1];
}
void Cpref(pop)(con_t *v)
{
if (v->length == 0) return;
v->length--;
}
void Cpref(erase)(con_t *v, size_t i)
{
assert(v->length > i);
memmove(v->data + i, v->data + i + 1,
sizeof(v->data[0]) * (v->length - 1 - i));
v->length--;
}
void Cpref(insert)(con_t *v, size_t i, val_t x)
{
Cpref(grow)(v, 1);
assert(v->length > i);
memmove(v->data + i + 1, v->data + i,
sizeof(v->data[0]) * (v->length - i));
v->data[i] = x;
v->length++;
}
void Cpref(clear)(con_t *v)
{
v->length = 0;
}
size_t Cpref(size)(con_t *v)
{
return v->length;
}
void Cpref(free)(con_t *v)
{
free(v->data);
}
#undef Ccat3
#undef Ccat2
#undef Cpref
#undef con_t
#undef val_t