timer: clean up hook allocator API
[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 struct timers_with_counters {
7         struct timers timers;
8         size_t num_alloc, num_free;
9 };
10
11
12 static void *test_alloc(struct timers *timers, size_t len)
13 {
14         ((struct timers_with_counters *)timers)->num_alloc++;
15         return malloc(len);
16 }
17
18 static void test_free(struct timers *timers, void *p)
19 {
20         if (p) {
21                 ((struct timers_with_counters *)timers)->num_free++;
22                 free(p);
23         }
24 }
25
26 static struct timemono timemono_from_nsec(unsigned long long nsec)
27 {
28         struct timemono epoch = { { 0, 0 } };
29         return timemono_add(epoch, time_from_nsec(nsec));
30 }
31
32 int main(void)
33 {
34         struct timers_with_counters tc;
35         struct timer t[64];
36         const struct timemono epoch = { { 0, 0 } };
37
38         tc.num_alloc = tc.num_free = 0;
39         plan_tests(12);
40
41         timers_set_allocator(test_alloc, test_free);
42         timers_init(&tc.timers, epoch);
43         timer_init(&t[0]);
44
45         timer_addmono(&tc.timers, &t[0],
46                       timemono_from_nsec(TIMER_GRANULARITY << TIMER_LEVEL_BITS));
47         timers_expire(&tc.timers, timemono_from_nsec(1));
48         ok1(tc.num_alloc == 1);
49         ok1(tc.num_free == 0);
50         timer_del(&tc.timers, &t[0]);
51         ok1(tc.num_alloc == 1);
52         ok1(tc.num_free == 0);
53         timers_cleanup(&tc.timers);
54         ok1(tc.num_alloc == 1);
55         ok1(tc.num_free == 1);
56
57         /* Should restore defaults */
58         timers_set_allocator(NULL, NULL);
59         ok1(timer_alloc == timer_default_alloc);
60         ok1(timer_free == timer_default_free);
61
62         timers_init(&tc.timers, epoch);
63         timer_addmono(&tc.timers, &t[0],
64                       timemono_from_nsec(TIMER_GRANULARITY << TIMER_LEVEL_BITS));
65         ok1(tc.num_alloc == 1);
66         ok1(tc.num_free == 1);
67         timers_cleanup(&tc.timers);
68         ok1(tc.num_alloc == 1);
69         ok1(tc.num_free == 1);
70
71         /* This exits depending on whether all tests passed */
72         return exit_status();
73 }