]> git.ozlabs.org Git - ccan/blob - ccan/tdb2/test/run-hashclash.c
tdb2: tdb_append implemented, beef up tests.
[ccan] / ccan / tdb2 / test / run-hashclash.c
1 #include <ccan/tdb2/tdb.c>
2 #include <ccan/tdb2/free.c>
3 #include <ccan/tdb2/lock.c>
4 #include <ccan/tdb2/io.c>
5 #include <ccan/tdb2/check.c>
6 #include <ccan/tap/tap.h>
7 #include "logging.h"
8
9 /* We rig the hash so adjacent-numbered records always clash. */
10 static uint64_t clash(const void *key, size_t len, uint64_t seed, void *priv)
11 {
12         return *(unsigned int *)key / 2;
13 }
14
15 static void test_val(struct tdb_context *tdb, unsigned int val)
16 {
17         unsigned int v;
18         struct tdb_data key = { (unsigned char *)&v, sizeof(v) };
19         struct tdb_data data = { (unsigned char *)&v, sizeof(v) };
20
21         /* Insert two entries, with the same hash. */
22         v = val;
23         ok1(tdb_store(tdb, key, data, TDB_INSERT) == 0);
24         v = val + 1;
25         ok1(tdb_store(tdb, key, data, TDB_INSERT) == 0);
26         ok1(tdb_check(tdb, NULL, NULL) == 0);
27
28         /* Can find both? */
29         v = val;
30         ok1(tdb_fetch(tdb, key).dsize == data.dsize);
31         v = val + 1;
32         ok1(tdb_fetch(tdb, key).dsize == data.dsize);
33 }
34
35 int main(int argc, char *argv[])
36 {
37         unsigned int i;
38         struct tdb_context *tdb;
39         union tdb_attribute hattr = { .hash = { .base = { TDB_ATTRIBUTE_HASH },
40                                                 .hash_fn = clash } };
41         int flags[] = { TDB_INTERNAL, TDB_DEFAULT, TDB_NOMMAP,
42                         TDB_INTERNAL|TDB_CONVERT, TDB_CONVERT,
43                         TDB_NOMMAP|TDB_CONVERT,
44         };
45
46         hattr.base.next = &tap_log_attr;
47
48         plan_tests(sizeof(flags) / sizeof(flags[0]) * 14 + 1);
49         for (i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) {
50                 tdb = tdb_open("run-hashclash.tdb", flags[i],
51                                O_RDWR|O_CREAT|O_TRUNC, 0600, &hattr);
52                 ok1(tdb);
53                 if (!tdb)
54                         continue;
55
56                 /* Check start of hash table. */
57                 test_val(tdb, 0);
58
59                 ok1(!tdb_has_locks(tdb));
60                 tdb_close(tdb);
61
62                 tdb = tdb_open("run-hashclash.tdb", flags[i],
63                                O_RDWR|O_CREAT|O_TRUNC, 0600, &hattr);
64                 ok1(tdb);
65                 if (!tdb)
66                         continue;
67
68                 /* Check end of hash table (will wrap around!). */
69                 test_val(tdb, ((1 << tdb->header.v.hash_bits) - 1) * 2);
70
71                 ok1(!tdb_has_locks(tdb));
72                 tdb_close(tdb);
73         }
74
75         ok1(tap_log_messages == 0);
76         return exit_status();
77 }