]> git.ozlabs.org Git - ccan/blob - ccan/alloc/test/run-testsize.c
talloc: fix leak in test/run-set_allocator.c
[ccan] / ccan / alloc / test / run-testsize.c
1 #include <ccan/alloc/alloc.h>
2 #include <ccan/tap/tap.h>
3 #include <ccan/alloc/alloc.c>
4 #include <ccan/alloc/bitops.c>
5 #include <ccan/alloc/tiny.c>
6 #include <stdlib.h>
7 #include <stdbool.h>
8 #include <err.h>
9
10 static void invert_bytes(unsigned char *p, unsigned long size)
11 {
12         unsigned int i;
13
14         for (i = 0; i < size; i++)
15                 p[i] ^= 0xFF;
16 }
17
18 static bool sizes_ok(void *mem, unsigned long poolsize, void *p[], unsigned num)
19 {
20         unsigned int i;
21
22         for (i = 0; i < num; i++)
23                 if (p[i] && alloc_size(mem, poolsize, p[i]) < i)
24                         return false;
25         return true;
26 }
27
28 static void test_pool(unsigned long pool_size)
29 {
30         unsigned int i, num;
31         void *mem;
32         void **p;
33         bool flip = false;
34
35         p = calloc(pool_size, sizeof(void *));
36         mem = malloc(pool_size);
37
38         alloc_init(mem, pool_size);
39
40         /* Check that alloc_size() gives reasonable answers. */
41         for (i = 0; i < pool_size; i = i * 3 / 2 + 1) {
42                 p[i] = alloc_get(mem, pool_size, i, 1);
43                 if (!p[i])
44                         break;
45                 invert_bytes(p[i], alloc_size(mem, pool_size, p[i]));
46         }
47         ok1(i < pool_size);
48         num = i;
49         ok1(alloc_check(mem, pool_size));
50         ok1(sizes_ok(mem, pool_size, p, num));
51
52         /* Free every second one. */
53         for (i = 0; i < num; i = i * 3 / 2 + 1) {
54                 flip = !flip;
55                 if (flip) {
56                         invert_bytes(p[i], alloc_size(mem,pool_size,p[i]));
57                         continue;
58                 }
59                 alloc_free(mem, pool_size, p[i]);
60                 p[i] = NULL;
61         }
62         ok1(alloc_check(mem, pool_size));
63         ok1(sizes_ok(mem, pool_size, p, num));
64         free(p);
65         free(mem);
66 }
67
68 int main(int argc, char *argv[])
69 {
70         plan_tests(10);
71
72         /* Large test. */
73         test_pool(MIN_USEFUL_SIZE * 2);
74
75         /* Small test. */
76         test_pool(MIN_USEFUL_SIZE / 2);
77
78         return exit_status();
79 }