75e1af06bc3fc53c1cc48390fcfc07ee84c9e748
[ccan] / ccan / timer / test / run-allocator.c
1 #define CCAN_TIMER_DEBUG
2 /* Include the C files directly. */
3 #include <ccan/timer/timer.c>
4 #include <ccan/tap/tap.h>
5
6 static void *test_alloc(size_t len, void *arg)
7 {
8         (*(size_t *)arg)++;
9         return malloc(len);
10 }
11
12 static void test_free(const void *p, void *arg)
13 {
14         if (p) {
15                 (*(size_t *)arg)--;
16                 free((void *)p);
17         }
18 }
19
20 static struct timemono timemono_from_nsec(unsigned long long nsec)
21 {
22         struct timemono epoch = { { 0, 0 } };
23         return timemono_add(epoch, time_from_nsec(nsec));
24 }
25
26 int main(void)
27 {
28         struct timers timers;
29         struct timer t[64];
30         size_t num_allocs = 0;
31         const struct timemono epoch = { { 0, 0 } };
32
33         plan_tests(7);
34
35         timers_set_allocator(test_alloc, test_free, &num_allocs);
36         timers_init(&timers, epoch);
37         timer_init(&t[0]);
38
39         timer_addmono(&timers, &t[0],
40                       timemono_from_nsec(TIMER_GRANULARITY << TIMER_LEVEL_BITS));
41         timers_expire(&timers, timemono_from_nsec(1));
42         ok1(num_allocs == 1);
43         timer_del(&timers, &t[0]);
44         ok1(num_allocs == 1);
45         timers_cleanup(&timers);
46         ok1(num_allocs == 0);
47
48         /* Should restore defaults */
49         timers_set_allocator(NULL, NULL, NULL);
50         ok1(timer_alloc == timer_default_alloc);
51         ok1(timer_free == timer_default_free);
52
53         timers_init(&timers, epoch);
54         timer_addmono(&timers, &t[0],
55                       timemono_from_nsec(TIMER_GRANULARITY << TIMER_LEVEL_BITS));
56         ok1(num_allocs == 0);
57         timers_cleanup(&timers);
58         ok1(num_allocs == 0);
59
60         /* This exits depending on whether all tests passed */
61         return exit_status();
62 }