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

/* provide generic any that matches anything/everything */
typedef any {}

#include "map.h"

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

/* int wrapper, provides cmp/hash for a generic integer type
 * (here a trait like is_integer would be ideal but oh well) */
typedef intw[any I]() {
	typedef <I> <>;

	size_t <>_hash(<> *a)
	{
		/* identity hash */
		return *a;
	}

	int <>_cmp(<> *a, <> *b)
	{
		return *a - *b;
	}
};

/* create wrapper for ints. */
typedef intw = intw[int]();

/* create hashmap of ints, using the intw wrapper we just created. Kind of
 * boilerplatey, admittedly. */
typedef ints = map[intw, intw]();

int main()
{
	/* heuristic, but if we know how many elements we'll need, we should
	 * give it to the create function. */
	ints ints = ints_create(0);
	for (int i = 0; i < 1000000; ++i) {
		ints_insert(&ints, i, i);
	}
	assert(ints_len(&ints) == 1000000);

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

	size_t count = 0;
	foreach(ints, iter, &ints) {
		assert(iter->key == iter->data);
		count++;
	}

	assert(count == 1000000);

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

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