tdb2: feature support.
[ccan] / ccan / tdb2 / test / run-30-exhaust-before-expand.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/tdb2/hash.c>
7 #include <ccan/tdb2/transaction.c>
8 #include <ccan/tap/tap.h>
9 #include <err.h>
10 #include "logging.h"
11
12 static bool empty_freetable(struct tdb_context *tdb)
13 {
14         struct tdb_freetable ftab;
15         unsigned int i;
16
17         /* Now, free table should be completely exhausted in zone 0 */
18         if (tdb_read_convert(tdb, tdb->ftable_off, &ftab, sizeof(ftab)) != 0)
19                 abort();
20
21         for (i = 0; i < sizeof(ftab.buckets)/sizeof(ftab.buckets[0]); i++) {
22                 if (ftab.buckets[i])
23                         return false;
24         }
25         return true;
26 }
27
28
29 int main(int argc, char *argv[])
30 {
31         unsigned int i, j;
32         struct tdb_context *tdb;
33         int flags[] = { TDB_INTERNAL, TDB_DEFAULT, TDB_NOMMAP,
34                         TDB_INTERNAL|TDB_CONVERT, TDB_CONVERT,
35                         TDB_NOMMAP|TDB_CONVERT };
36
37         plan_tests(sizeof(flags) / sizeof(flags[0]) * 9 + 1);
38
39         for (i = 0; i < sizeof(flags) / sizeof(flags[0]); i++) {
40                 TDB_DATA k;
41                 uint64_t size;
42                 bool was_empty = false;
43
44                 k.dptr = (void *)&j;
45                 k.dsize = sizeof(j);
46
47                 tdb = tdb_open("run-30-exhaust-before-expand.tdb", flags[i],
48                                O_RDWR|O_CREAT|O_TRUNC, 0600, &tap_log_attr);
49                 ok1(tdb);
50                 if (!tdb)
51                         continue;
52
53                 ok1(empty_freetable(tdb));
54                 /* Need some hash lock for expand. */
55                 ok1(tdb_lock_hashes(tdb, 0, 1, F_WRLCK, TDB_LOCK_WAIT) == 0);
56                 /* Create some free space. */
57                 ok1(tdb_expand(tdb, 1) == 0);
58                 ok1(tdb_unlock_hashes(tdb, 0, 1, F_WRLCK) == 0);
59                 ok1(tdb_check(tdb, NULL, NULL) == 0);
60                 ok1(!empty_freetable(tdb));
61
62                 size = tdb->map_size;
63                 /* Insert minimal-length records until we expand. */
64                 for (j = 0; tdb->map_size == size; j++) {
65                         was_empty = empty_freetable(tdb);
66                         if (tdb_store(tdb, k, k, TDB_INSERT) != 0)
67                                 err(1, "Failed to store record %i", j);
68                 }
69
70                 /* Would have been empty before expansion, but no longer. */
71                 ok1(was_empty);
72                 ok1(!empty_freetable(tdb));
73                 tdb_close(tdb);
74         }
75
76         ok1(tap_log_messages == 0);
77         return exit_status();
78 }