9d3a94e60b323a188b3f3f3bcb5d859ad942591f
[ccan] / ccan / tal / test / run-destructor.c
1 #include <ccan/tal/tal.h>
2 #include <ccan/tal/tal.c>
3 #include <ccan/tap/tap.h>
4
5 static char *parent, *child;
6 static int destroy_count;
7
8 /* Parent gets destroyed first. */
9 static void destroy_parent(char *p)
10 {
11         ok1(p == parent);
12         ok1(destroy_count == 0);
13         /* Can still access child. */
14         *child = '1';
15         destroy_count++;
16 }
17
18 static void destroy_child(char *p)
19 {
20         ok1(p == child);
21         ok1(destroy_count == 1);
22         /* Can still access parent (though destructor has been called). */
23         *parent = '1';
24         destroy_count++;
25 }
26
27 static void destroy_inc(char *p)
28 {
29         destroy_count++;
30 }
31
32 int main(void)
33 {
34         char *child2;
35
36         plan_tests(12);
37
38         parent = tal(NULL, char);
39         child = tal(parent, char);
40         ok1(tal_add_destructor(parent, destroy_parent));
41         ok1(tal_add_destructor(child, destroy_child));
42
43         tal_free(parent);
44         ok1(destroy_count == 2);
45
46         parent = tal(NULL, char);
47         child = tal(parent, char);
48         child2 = tal(parent, char);
49         ok1(tal_add_destructor(parent, destroy_inc));
50         ok1(tal_add_destructor(parent, destroy_inc));
51         ok1(tal_add_destructor(child, destroy_inc));
52         ok1(tal_add_destructor(child2, destroy_inc));
53         tal_free(parent);
54         ok1(destroy_count == 6);
55
56         return exit_status();
57 }