]> git.ozlabs.org Git - ccan/blob - ccan/coroutine/test/api-3.c
e06c03d3c47f2eec23e4dd9c0bee666ecd1ee0f6
[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         diag("Wrote random to buffer\n");
31
32         s->total = 0;
33         for (i = 0; i < sizeof(buf); i++) {
34                 s->total += buf[i];
35         }
36
37         coroutine_jump(&s->ret);
38 }
39
40 static void test_metadata(struct coroutine_stack *stack)
41 {
42         struct metadata *meta;
43
44         meta = coroutine_stack_to_metadata(stack, sizeof(*meta));
45         ok1(coroutine_stack_from_metadata(meta, sizeof(*meta)) == stack);
46
47         meta->magic = META_MAGIC;
48         ok1(meta->magic == META_MAGIC);
49
50         if (COROUTINE_AVAILABLE) {
51                 struct coroutine_state t;
52                 struct state s = {
53                 };
54
55                 coroutine_init(&t, clobber, &s, stack);
56                 coroutine_switch(&s.ret, &t);
57                 ok1(s.total != 0);
58         } else {
59                 skip(1, "Coroutines not available");
60         }
61
62         ok1(coroutine_stack_to_metadata(stack, sizeof(*meta)) == meta);
63         ok1(coroutine_stack_from_metadata(meta, sizeof(*meta)) == stack);
64         ok1(meta->magic == META_MAGIC);
65 }
66
67 int main(void)
68 {
69         char buf[BUFSIZE];
70         struct coroutine_stack *stack;
71
72         /* This is how many tests you plan to run */
73         plan_tests(9);
74
75         /* Fix seed so we get consistent, though pseudo-random results */       
76         srandom(0);
77
78         stack = coroutine_stack_init(buf, sizeof(buf), sizeof(struct metadata));
79         ok1(stack != NULL);
80         ok1(coroutine_stack_check(stack, NULL) == stack);
81         ok1(coroutine_stack_size(stack)
82             == BUFSIZE - COROUTINE_STK_OVERHEAD - sizeof(struct metadata));
83
84         test_metadata(stack);
85
86         coroutine_stack_release(stack, sizeof(struct metadata));
87
88         /* This exits depending on whether all tests passed */
89         return exit_status();
90 }