a6e667bbae0875104725d36f676a95083d31d388
[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(24);
10
11         /* We can take NULL. */
12         ok1(take(NULL) == NULL);
13         ok1(taken(NULL)); /* Undoes take() */
14         ok1(!taken(NULL));
15
16         parent = tal(NULL, char);
17         ok1(parent);
18
19         ok1(take(parent) == parent);
20         ok1(taken(parent)); /* Undoes take() */
21         ok1(!taken(parent));
22
23         c = tal_strdup(parent, "hello");
24
25         c = tal_strdup(parent, take(c));
26         ok1(strcmp(c, "hello") == 0);
27         ok1(tal_parent(c) == parent);
28
29         c = tal_strndup(parent, take(c), 5);
30         ok1(strcmp(c, "hello") == 0);
31         ok1(tal_parent(c) == parent);
32
33         c = tal_strndup(parent, take(c), 3);
34         ok1(strcmp(c, "hel") == 0);
35         ok1(tal_parent(c) == parent);
36
37         c = tal_dup(parent, char, take(c), 1, 0);
38         ok1(c[0] == 'h');
39         ok1(tal_parent(c) == parent);
40
41         c = tal_dup(parent, char, take(c), 1, 2);
42         ok1(c[0] == 'h');
43         strcpy(c, "hi");
44         ok1(tal_parent(c) == parent);
45
46         /* dup must reparent child. */
47         c = tal_dup(NULL, char, take(c), 1, 0);
48         ok1(c[0] == 'h');
49         ok1(tal_parent(c) == NULL);
50
51         /* No leftover allocations. */
52         tal_free(c);
53         ok1(tal_first(parent) == NULL);
54
55         c = tal_strdup(parent, "hello %s");
56         c = tal_asprintf(parent, take(c), "there");
57         ok1(strcmp(c, "hello there") == 0);
58         ok1(tal_parent(c) == parent);
59         /* No leftover allocations. */
60         tal_free(c);
61         ok1(tal_first(parent) == NULL);
62
63         tal_free(parent);
64         ok1(!taken_any());
65
66         return exit_status();
67 }