blob: 8076155b5499e1a68901b386657b62b399ac5351 (
plain)
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
|
/* libmisc/tests/test_rand.c - Tests for <libmisc/rand.h>
*
* Copyright (C) 2024 Luke T. Shumaker <lukeshu@lukeshu.com>
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
#include <stdbool.h>
#include <setjmp.h>
#include <libmisc/rand.h>
#include <libmisc/_intercept.h>
#include "test.h"
/* Intercept failures *********************************************************/
#ifndef NDEBUG
jmp_buf *__catch;
void __lm_abort(void) {
if (__catch)
longjmp(*__catch, 1);
abort();
}
#define should_abort(cmd) do { \
jmp_buf *old_catch = __catch; \
jmp_buf env; \
__catch = &env; \
if (!setjmp(env)) { \
cmd; \
__catch = old_catch; \
test_assert(false); \
} else { \
__catch = old_catch; \
} \
} while (0);
#endif
/* Actual tests ***************************************************************/
#define ROUNDS 4096
#define MAX_SEE_ALL 128
static void test_n(uint64_t cnt) {
if (cnt == 0 || cnt > UINT64_C(1)<<63) {
#ifndef NDEBUG
should_abort(rand_uint63n(cnt));
#else
return;
#endif
} else {
double sum = 0;
bool seen[MAX_SEE_ALL] = {0};
for (int i = 0; i < ROUNDS; i++) {
uint64_t val = rand_uint63n(cnt);
sum += val;
test_assert(val < cnt);
if (cnt < MAX_SEE_ALL)
seen[val] = true;
}
if (cnt > 1) {
test_assert(sum/ROUNDS > 0.45*(cnt-1));
test_assert(sum/ROUNDS < 0.55*(cnt-1));
}
if (cnt < MAX_SEE_ALL) {
for (uint64_t i = 0; i < cnt; i++)
test_assert(seen[i]);
}
}
}
int main() {
for (uint8_t i = 0; i < 64; i++)
test_n(UINT64_C(1)<<i);
for (uint64_t j = 0; j < MAX_SEE_ALL; j++)
test_n(j);
return 0;
}
|