tal: handle take() pointers more carefully.
[ccan] / ccan / tal / test / run-take.c
1 #include <ccan/tal/tal.h>
2 #include <ccan/tal/tal.c>
3 #include <ccan/tap/tap.h>
4
5 int main(void)
6 {
7         char *parent, *c;
8
9         plan_tests(22);
10
11         /* We can take NULL. */
12         ok1(take(NULL) == NULL);
13         ok1(is_taken(NULL));
14         ok1(taken(NULL)); /* Undoes take() */
15         ok1(!is_taken(NULL));
16         ok1(!taken(NULL));
17
18         parent = tal(NULL, char);
19         ok1(parent);
20
21         ok1(take(parent) == parent);
22         ok1(is_taken(parent));
23         ok1(taken(parent)); /* Undoes take() */
24         ok1(!is_taken(parent));
25         ok1(!taken(parent));
26
27         c = tal(parent, char);
28         *c = 'h';
29         c = tal_dup(parent, char, take(c));
30         ok1(c[0] == 'h');
31         ok1(tal_parent(c) == parent);
32
33         c = tal_dup_arr(parent, char, take(c), 1, 2);
34         ok1(c[0] == 'h');
35         strcpy(c, "hi");
36         ok1(tal_parent(c) == parent);
37
38         /* dup must reparent child. */
39         c = tal_dup(NULL, char, take(c));
40         ok1(c[0] == 'h');
41         ok1(tal_parent(c) == NULL);
42
43         /* No leftover allocations. */
44         tal_free(c);
45         ok1(tal_first(parent) == NULL);
46
47         /* tal_resize should return a taken pointer. */
48         c = take(tal_arr(parent, char, 5));
49         tal_resize(&c, 100);
50         ok1(taken(c));
51         tal_free(c);
52
53         tal_free(parent);
54         ok1(!taken_any());
55
56         /* NULL pass-through. */
57         c = NULL;
58         ok1(tal_dup_arr(NULL, char, take(c), 5, 5) == NULL);
59         ok1(!taken_any());
60
61         tal_cleanup();
62         return exit_status();
63 }