]> git.ozlabs.org Git - ccan/blob - ccan/htable/test/run-zero-hash-first-entry.c
htable: fix bug where first entry has hash of 0 or 1.
[ccan] / ccan / htable / test / run-zero-hash-first-entry.c
1 #include <ccan/htable/htable.h>
2 #include <ccan/htable/htable.c>
3 #include <ccan/tap/tap.h>
4 #include <stdbool.h>
5
6 struct data {
7         size_t key;
8 };
9
10 /* Hash is simply key itself. */
11 static size_t hash(const void *e, void *unused)
12 {
13         struct data *d = (struct data *)e;
14
15         return d->key;
16 }
17
18 static bool eq(const void *e, void *k)
19 {
20         struct data *d = (struct data *)e;
21         size_t *key = (size_t *)k;
22
23         return (d->key == *key);
24 }
25
26 int main(void)
27 {
28         struct htable table;
29         struct data *d0, *d1;
30
31         plan_tests(6);
32
33         d1 = malloc(sizeof(struct data));
34         d1->key = 1;
35         d0 = malloc(sizeof(struct data));
36         d0->key = 0;
37
38         htable_init(&table, hash, NULL);
39
40         htable_add(&table, d0->key, d0);
41         htable_add(&table, d1->key, d1);
42
43         ok1(table.elems == 2);
44         ok1(htable_get(&table, 1, eq, &d1->key) == d1);
45         ok1(htable_get(&table, 0, eq, &d0->key) == d0);
46         htable_clear(&table);
47
48         /* Now add in reverse order, should still be OK. */
49         htable_add(&table, d1->key, d1);
50         htable_add(&table, d0->key, d0);
51
52         ok1(table.elems == 2);
53         ok1(htable_get(&table, 1, eq, &d1->key) == d1);
54         ok1(htable_get(&table, 0, eq, &d0->key) == d0);
55         htable_clear(&table);
56
57         free(d0);
58         free(d1);
59         return exit_status();
60 }
61