aboutsummaryrefslogtreecommitdiff
path: root/examples/vec.fwd
blob: 1cc10b3fbf4dc36f679f4eac08c98a2239a47a9b (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
import "../mod/libfwdmem.so"
import "../mod/libfwdutil.so"

/* trait */
any = {}

/* template */
vec[any type]() {
	<> {
		i64 s;
		i64 n;
		*[]type buf;
	}

	<>create((<>) next)
	{
		next((0 => s, 0 => n, * => buf)<>);
	}

	<>append(<> v, type n, (<>) next)
	{
		v.n = v.n + 1;
		if v.s == 0 {
			v.s = 1;
		}

		if v.n > v.s {
			if v.s == 0 {
				v.s = 1;
			}

			v.s = v.s * 2;
			fwdrealloc(v.buf, v.s as u64 * sizeof(type)) => ptr;
			v.buf = ptr;
		}

		/* in a real implementation this would be moved to after
		 * fwdrealloc I guess, but this is fine for now */
		nil v.buf {fwdpanic("no buf for vector");} => buf;
		buf*[v.n - 1] = n;
		next(v);
	}

	<>destroy(<> v)
	{
		fwdfree(v.buf);
		nil v;
	}
}

u8vec = vec[u8]()