summaryrefslogtreecommitdiff
path: root/tests/sptree.c
blob: 9eff356c6e2cf1033569e65b99a8e17e1462e2fc (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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#include <assert.h>
#include <stdlib.h>
#include <stdio.h>
#include "test.h"

/* required defs */
#define SPTREE_TYPE int
#define SPTREE_CMP(a, b) ((b) - (a))
#define SPTREE_NAME ints

/* optional defs */
#define SPTREE_MALLOC mallocc
#define SPTREE_CALLOC callocc
#define SPTREE_REALLOC reallocc
#define SPTREE_FREE free

#include <conts/sptree.h>

int main()
{
#if defined(COVERAGE)
	assert(!covsrv_init());
	atexit(covsrv_destroy);
#endif

	struct ints ints = ints_create();
	/* check that iterating an empty tree doesn't do anything */
	foreach(ints, iter, &ints) {
		assert(false && "iterating empty tree");
	}

	for (int i = 0; i < 1000000; ++i) {
		if (!ints_insert(&ints, i)) {
			fprintf(stderr, "failed inserting %d\n", i);
			ints_destroy(&ints);
			return -1;
		}
	}
	assert(ints_len(&ints) == 1000000);

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

	/* check that inserting duplicate returns the original */
	int *orig = ints_find(&ints, 0);
	ints_insert(&ints, 0);
	assert(ints_find(&ints, 0) == orig);

	int i = 0;
	foreach(ints, iter, &ints) {
		/* since my trees are ordered, this must hold, although you
		 * might consider it an implementation detail that shouldn't be
		 * relied on */
		assert(iter && *iter == i);
		i++;
	}

	for (int i = 0; i < 1000000; ++i) {
		ints_remove(&ints, i);
	}

	assert(ints_len(&ints) == 0);

	/* check that removing nonexistant item (or empty tree) doesn't crash */
	ints_remove(&ints, 0);

	/* insert random integers to hopefully exercise the code a bit more */
	srand(0);

	int inserted[1000];
	for (int i = 0; i < 1000; ++i) {
		inserted[i] = rand();

		/* covsrv shouldn't fail anymore */
		assert(ints_insert(&ints, inserted[i]));
	}

	for (int i = 0; i < 1000; ++i) {
		int *v = ints_find(&ints, inserted[i]);
		assert(v && *v == inserted[i]);
	}

	for (int i = 0; i < 1000; ++i) {
		ints_remove(&ints, inserted[i]);
	}

	assert(ints_len(&ints) == 0);


	ints_destroy(&ints);
}