MULE 0.0.1
Multi-Use Library Essentials
Loading...
Searching...
No Matches
rand.h
1#pragma once
2/**
3 * @defgroup mod_rand Rand
4 * @brief A small, fast, seeded pseudo-random generator.
5 *
6 * The generator is splitmix64, so the same seed gives the same sequence on
7 * every platform, unlike rand(). Use it for tests, simulations and shuffles,
8 * where a failure must be reproducible from its seed.
9 *
10 * - A zero-initialised Rand is valid. Set `state` to pick a seed.
11 * - Each Rand is independent and holds no global state. Copy one to fork
12 * its sequence.
13 * - rand_below() is unbiased. It rejects the few values that would make
14 * some results more likely than others, instead of a plain `% n`.
15 *
16 * @snippet{trimleft} test_rand.c rand
17 *
18 * @warning Not for secrets. The sequence is predictable from one output.
19 * Use the operating system's generator for keys and tokens.
20 * @{
21 */
22
23#include "base/base.h"
24
25/** Generator state. Copy it to fork a sequence. */
26typedef struct Rand {
27 uint64_t state; /**< The seed, advanced by every call. */
28} Rand;
29
30/** The next 64 random bits. */
31MULE_NODISCARD uint64_t rand_next(Rand *r);
32/** A uniform value in [0, @p n).
33 * @pre @p n is not 0. An assert checks it. */
34MULE_NODISCARD uint64_t rand_below(Rand *r, uint64_t n);
35
36/** @} */
uint64_t state
The seed, advanced by every call.
Definition rand.h:27
uint64_t rand_below(Rand *r, uint64_t n)
A uniform value in [0, n).
Definition rand.c:12
uint64_t rand_next(Rand *r)
The next 64 random bits.
Definition rand.c:5
Generator state.
Definition rand.h:26