]> git.ozlabs.org Git - ccan/blob - ccan/coroutine/test/api-3.c
4b90b46310b2952ba2a780ac72089db842670496
[ccan] / ccan / coroutine / test / api-3.c
1 #include <stdlib.h>
2
3 #include <ccan/coroutine/coroutine.h>
4 #include <ccan/tap/tap.h>
5
6 /* Test metadata */
7 #define META_MAGIC 0x4d86aa82ec1892f6
8 #define BUFSIZE    8192
9
10 struct metadata {
11         uint64_t magic;
12 };
13
14 struct state {
15         struct coroutine_state ret;
16         unsigned long total;
17 };
18
19 /* Touch a bunch of stack */
20 static void clobber(void *p)
21 {
22         struct state *s = (struct state *)p;
23         char buf[BUFSIZE - COROUTINE_MIN_STKSZ];
24         int i;
25
26         for (i = 0; i < sizeof(buf); i++) {
27                 buf[i] = random() & 0xff;
28         }
29
30         for (i = 0; i < sizeof(buf); i++) {
31                 s->total += buf[i];
32         }
33
34         coroutine_jump(&s->ret);
35 }
36
37 static void test_metadata(struct coroutine_stack *stack)
38 {
39         struct metadata *meta;
40
41         meta = coroutine_stack_to_metadata(stack, sizeof(*meta));
42         ok1(coroutine_stack_from_metadata(meta, sizeof(*meta)) == stack);
43
44         meta->magic = META_MAGIC;
45         ok1(meta->magic == META_MAGIC);
46
47         if (COROUTINE_AVAILABLE) {
48                 struct coroutine_state t;
49                 struct state s = {
50                         .total = 0,
51                 };
52
53                 coroutine_init(&t, clobber, &s, stack);
54                 coroutine_switch(&s.ret, &t);
55                 ok1(s.total != 0);
56         } else {
57                 skip(1, "Coroutines not available");
58         }
59
60         ok1(coroutine_stack_to_metadata(stack, sizeof(*meta)) == meta);
61         ok1(coroutine_stack_from_metadata(meta, sizeof(*meta)) == stack);
62         ok1(meta->magic == META_MAGIC);
63 }
64
65 int main(void)
66 {
67         char *buf;
68         struct coroutine_stack *stack;
69
70         /* This is how many tests you plan to run */
71         plan_tests(10);
72
73         /* Fix seed so we get consistent, though pseudo-random results */       
74         srandom(0);
75
76         buf = malloc(BUFSIZE);
77         ok1(buf != NULL);
78
79         stack = coroutine_stack_init(buf, BUFSIZE, sizeof(struct metadata));
80         ok1(stack != NULL);
81         ok1(coroutine_stack_check(stack, NULL) == stack);
82         ok1(coroutine_stack_size(stack)
83             == BUFSIZE - COROUTINE_STK_OVERHEAD - sizeof(struct metadata));
84
85         test_metadata(stack);
86
87         coroutine_stack_release(stack, sizeof(struct metadata));
88
89         free(buf);
90
91         /* This exits depending on whether all tests passed */
92         return exit_status();
93 }