aboutsummaryrefslogtreecommitdiff
path: root/example_vec/new/main.c
blob: a75628157217a6ea32608e8f53b0955a36f6f45a (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
#include <stdio.h>

/* an empty trait matches anything, this would presumably be defined in a
 * library somewhere and then included everywhere */
typedef any {}

#include "vec.h"

#define foreach(name, i, s) \
	for (name##_iter i = name##_begin(s); !name##_end(s, i); i = name##_next(i))

/* traits aren't really implemented fully yet but this would check for a
 * function like <>_add(<> a, <> b) or something along those lines */
typedef summable {}

typedef summable_vec[summable type]() = vec[<type>](){
	<type> <>_sum(struct <> *v) {
		<type> sum = 0;
		for (size_t i = 0; i < v->n; ++i) {
			sum += v->buf[i];
		}

		return sum;
	}
};

typedef ints = summable_vec[int]();

int main()
{
	struct ints ints = ints_create(0);
	for (int i = 0; i < 1000000; ++i) {
		ints_append(&ints, i);
	}
	assert(ints_len(&ints) == 1000000);

	for (int i = 0; i < 1000000; ++i) {
		int *v = ints_at(&ints, i);
		assert(v && *v == i);
	}

	int i = 0;
	foreach(ints, iter, &ints) {
		assert(iter && *iter == i);
		i++;
	}

	/* probably not strictly portable but you get the idea */
	int sum = ints_sum(&ints);
	assert(sum == 1783293664);

	for (int i = 1000000 - 1; i >= 0; --i) {
		ints_remove(&ints, i);
	}
	assert(ints_len(&ints) == 0);

	ints_destroy(&ints);
}