9f0a22c6c4ea24bf6cae5b0701564573b7bdb347
[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(32);
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_strdup(parent, "hello");
28
29         c = tal_strdup(parent, take(c));
30         ok1(strcmp(c, "hello") == 0);
31         ok1(tal_parent(c) == parent);
32
33         c = tal_strndup(parent, take(c), 5);
34         ok1(strcmp(c, "hello") == 0);
35         ok1(tal_parent(c) == parent);
36
37         c = tal_strndup(parent, take(c), 3);
38         ok1(strcmp(c, "hel") == 0);
39         ok1(tal_parent(c) == parent);
40
41         c = tal_dup(parent, char, take(c), 1, 0);
42         ok1(c[0] == 'h');
43         ok1(tal_parent(c) == parent);
44
45         c = tal_dup(parent, char, take(c), 1, 2);
46         ok1(c[0] == 'h');
47         strcpy(c, "hi");
48         ok1(tal_parent(c) == parent);
49
50         /* dup must reparent child. */
51         c = tal_dup(NULL, char, take(c), 1, 0);
52         ok1(c[0] == 'h');
53         ok1(tal_parent(c) == NULL);
54
55         /* No leftover allocations. */
56         tal_free(c);
57         ok1(tal_first(parent) == NULL);
58
59         c = tal_strdup(parent, "hello %s");
60         c = tal_asprintf(parent, take(c), "there");
61         ok1(strcmp(c, "hello there") == 0);
62         ok1(tal_parent(c) == parent);
63         /* No leftover allocations. */
64         tal_free(c);
65         ok1(tal_first(parent) == NULL);
66
67         tal_free(parent);
68         ok1(!taken_any());
69
70         /* NULL pass-through. */
71         c = NULL;
72         ok1(tal_strdup(NULL, take(c)) == NULL);
73         ok1(tal_strndup(NULL, take(c), 5) == NULL);
74         ok1(tal_dup(NULL, char, take(c), 5, 5) == NULL);
75         ok1(tal_asprintf(NULL, take(c), 0) == NULL);
76
77         return exit_status();
78 }