]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/test/test-prioq.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[thirdparty/systemd.git] / src / test / test-prioq.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <stdlib.h>
4
5 #include "alloc-util.h"
6 #include "prioq.h"
7 #include "set.h"
8 #include "siphash24.h"
9 #include "util.h"
10
11 #define SET_SIZE 1024*4
12
13 static int unsigned_compare(const unsigned *a, const unsigned *b) {
14 return CMP(*a, *b);
15 }
16
17 static void test_unsigned(void) {
18 _cleanup_(prioq_freep) Prioq *q = NULL;
19 unsigned buffer[SET_SIZE], i, u, n;
20
21 srand(0);
22
23 assert_se(q = prioq_new(trivial_compare_func));
24
25 for (i = 0; i < ELEMENTSOF(buffer); i++) {
26 u = (unsigned) rand();
27 buffer[i] = u;
28 assert_se(prioq_put(q, UINT_TO_PTR(u), NULL) >= 0);
29
30 n = prioq_size(q);
31 assert_se(prioq_remove(q, UINT_TO_PTR(u), &n) == 0);
32 }
33
34 typesafe_qsort(buffer, ELEMENTSOF(buffer), unsigned_compare);
35
36 for (i = 0; i < ELEMENTSOF(buffer); i++) {
37 assert_se(prioq_size(q) == ELEMENTSOF(buffer) - i);
38
39 u = PTR_TO_UINT(prioq_pop(q));
40 assert_se(buffer[i] == u);
41 }
42
43 assert_se(prioq_isempty(q));
44 }
45
46 struct test {
47 unsigned value;
48 unsigned idx;
49 };
50
51 static int test_compare(const void *a, const void *b) {
52 const struct test *x = a, *y = b;
53
54 return CMP(x->value, y->value);
55 }
56
57 static void test_hash(const void *a, struct siphash *state) {
58 const struct test *x = a;
59
60 siphash24_compress(&x->value, sizeof(x->value), state);
61 }
62
63 static const struct hash_ops test_hash_ops = {
64 .hash = test_hash,
65 .compare = test_compare
66 };
67
68 static void test_struct(void) {
69 _cleanup_(prioq_freep) Prioq *q = NULL;
70 _cleanup_(set_freep) Set *s = NULL;
71 unsigned previous = 0, i;
72 struct test *t;
73
74 srand(0);
75
76 assert_se(q = prioq_new(test_compare));
77 assert_se(s = set_new(&test_hash_ops));
78
79 for (i = 0; i < SET_SIZE; i++) {
80 assert_se(t = new0(struct test, 1));
81 t->value = (unsigned) rand();
82
83 assert_se(prioq_put(q, t, &t->idx) >= 0);
84
85 if (i % 4 == 0)
86 assert_se(set_consume(s, t) >= 0);
87 }
88
89 while ((t = set_steal_first(s))) {
90 assert_se(prioq_remove(q, t, &t->idx) == 1);
91 assert_se(prioq_remove(q, t, &t->idx) == 0);
92 assert_se(prioq_remove(q, t, NULL) == 0);
93
94 free(t);
95 }
96
97 for (i = 0; i < SET_SIZE * 3 / 4; i++) {
98 assert_se(prioq_size(q) == (SET_SIZE * 3 / 4) - i);
99
100 assert_se(t = prioq_pop(q));
101 assert_se(prioq_remove(q, t, &t->idx) == 0);
102 assert_se(prioq_remove(q, t, NULL) == 0);
103 assert_se(previous <= t->value);
104
105 previous = t->value;
106 free(t);
107 }
108
109 assert_se(prioq_isempty(q));
110 assert_se(set_isempty(s));
111 }
112
113 int main(int argc, char* argv[]) {
114
115 test_unsigned();
116 test_struct();
117
118 return 0;
119 }