1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
|
#include <stdlib.h>
#include <stdio.h>
#include <ccan/heap/heap.h>
/* Include the C files directly. */
#include <ccan/heap/heap.c>
#include <ccan/tap/tap.h>
struct item {
void *foobar;
int v;
};
static bool heap_ok(const struct heap *h, heap_less_func_t less, int i)
{
int l, r;
l = 2 * i + 1;
r = l + 1;
if (l < h->len) {
if (less(h->data[l], h->data[i])) {
fprintf(stderr, "heap property violation\n");
return false;
}
if (!heap_ok(h, less, l))
return false;
}
if (r < h->len) {
if (less(h->data[r], h->data[i])) {
fprintf(stderr, "heap property violation\n");
return false;
}
if (!heap_ok(h, less, r))
return false;
}
return true;
}
static bool less(const struct item *a, const struct item *b)
{
return a->v < b->v;
}
static bool __less(const void *a, const void *b)
{
return less(a, b);
}
static bool more(const struct item *a, const struct item *b)
{
return a->v > b->v;
}
static bool __more(const void *a, const void *b)
{
return more(a, b);
}
static bool some_test(size_t n, bool is_less)
{
struct item *items = calloc(n, sizeof(*items));
struct item *item, *prev;
struct heap *h;
int i;
if (items == NULL) {
perror("items");
exit(EXIT_FAILURE);
}
if (is_less)
h = heap_init(__less);
else
h = heap_init(__more);
if (h == NULL) {
perror("heap_init");
exit(EXIT_FAILURE);
}
for (i = 0; i < n; i++) {
item = &items[i];
item->v = rand();
printf("pushing %d\n", item->v);
heap_push(h, item);
if (!heap_ok(h, is_less ? __less : __more, 0))
return false;
}
if (is_less) {
heap_ify(h, __more);
if (!heap_ok(h, __more, 0))
return false;
heap_ify(h, __less);
if (!heap_ok(h, __less, 0))
return false;
} else {
heap_ify(h, NULL);
if (!heap_ok(h, __more, 0))
return false;
}
for (i = 0; i < n; i++) {
item = heap_pop(h);
if (!heap_ok(h, is_less ? __less : __more, 0))
return false;
printf("popped %d\n", item->v);
if (i > 0) {
if (is_less) {
if (less(item, prev))
return false;
} else {
if (more(item, prev))
return false;
}
}
prev = item;
}
heap_free(h);
free(items);
return true;
}
int main(void)
{
plan_tests(3);
ok1(some_test(5000, true));
ok1(some_test(1, true));
ok1(some_test(33, false));
return exit_status();
}
|