compiler: RETURNS_NONNULL macro
[ccan] / ccan / tal / test / run-count.c
1 #include <ccan/tal/tal.h>
2 #include <ccan/tal/tal.c>
3 #include <ccan/tap/tap.h>
4
5 static bool move;
6 #define ALIGN (sizeof(void *)*2)
7
8 static void *my_alloc(size_t len)
9 {
10         char *ret = malloc(len + ALIGN);
11         memcpy(ret, &len, sizeof(len));
12         return ret + ALIGN;
13 }
14
15 static void my_free(void *p)
16 {
17         if (p)
18                 free((char *)p - ALIGN);
19 }
20
21 static void *my_realloc(void *old, size_t new_size)
22 {
23         char *ret;
24
25         /* Test what happens if we always move */
26         if (move) {
27                 size_t old_size = *(size_t *)((char *)old - ALIGN);
28                 ret = my_alloc(new_size);
29                 memcpy(ret, old, old_size > new_size ? new_size : old_size);
30                 my_free(old);
31         } else {
32                 ret = realloc((char *)old - ALIGN, new_size + ALIGN);
33                 memcpy(ret, &new_size, sizeof(new_size));
34                 ret += ALIGN;
35         }
36         return ret;
37 }
38
39 int main(void)
40 {
41         char *p1, *p2;
42         unsigned int i;
43
44         tal_set_backend(my_alloc, my_realloc, my_free, NULL);
45
46         plan_tests(2 + 19 * 3);
47
48         p1 = NULL;
49         ok1(tal_bytelen(p1) == 0);
50         ok1(tal_count(p1) == 0);
51
52         for (i = 0; i < 3; i++) {
53                 move = i;
54
55                 p1 = tal(NULL, char);
56                 ok1(p1);
57                 ok1(tal_count(p1) == 1);
58
59                 p2 = tal_arr(p1, char, 1);
60                 ok1(p2);
61                 ok1(tal_count(p2) == 1);
62                 ok1(tal_resize(&p2, 2));
63                 ok1(tal_count(p2) == 2);
64                 ok1(tal_check(NULL, NULL));
65                 tal_free(p2);
66
67                 /* Resize twice. */
68                 p2 = tal_arrz(p1, char, 7);
69                 ok1(p2);
70                 ok1(tal_count(p2) == 7);
71                 ok1(tal_check(NULL, NULL));
72                 tal_resize(&p2, 20);
73                 ok1(p2);
74                 ok1(tal_check(NULL, NULL));
75                 ok1(tal_count(p2) == 20);
76                 /* Tickles non-moving logic, as we do not update bounds. */
77                 if (i == 2)
78                         move = false;
79                 tal_resize(&p2, 300);
80                 ok1(p2);
81                 ok1(tal_check(NULL, NULL));
82                 ok1(tal_count(p2) == 300);
83                 ok1(tal_resize(&p2, 0));
84                 ok1(tal_count(p2) == 0);
85                 ok1(tal_check(NULL, NULL));
86                 tal_free(p2);
87                 tal_free(p1);
88         }
89
90         tal_cleanup();
91         return exit_status();
92 }