summaryrefslogtreecommitdiff
path: root/lib/rnd.h
blob: 222617a462b2c9f73d102e980794f43998b79651 (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
#ifndef lib_rnd_h
#define lib_rnd_h
/* Cesar project {{{
 *
 * Copyright (C) 2007 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    lib/rnd.h
 * \brief   Random Number Generator header.
 * \ingroup lib
 */

/** Random number generator context. */
struct lib_rnd_t
{
#define LIB_MT_N 624
    unsigned long state[LIB_MT_N];
    int state_index;
};
typedef struct lib_rnd_t lib_rnd_t;

/** Generate a integer which has a probability of \a prob to be greater than a
 * random 32 bit integer.  Works with 0.0 <= \a prob < 1.0. */
#define LIB_RND_RATIO(prob) ((u32) ((1ull << 32) * (prob)))

BEGIN_DECLS

void
lib_rnd_init (lib_rnd_t *ctx, u32 seed);
void
lib_rnd_init_by_array (lib_rnd_t *ctx, const u32 init_key[], int key_length);
u32
lib_rnd32 (lib_rnd_t *ctx);
uint
lib_rnd_uniform (lib_rnd_t *ctx, uint bound);
void
lib_rnd_buffer (lib_rnd_t *ctx, u8 *buf, uint buf_size);

/**
 * Return true with the wanted probability.
 * \param  ctx  the rnd context
 * \param  prob  probability integer returned by LIB_RND_RATIO
 * \return  true when lib_rnd32() < \p prob
 */
extern inline bool
lib_rnd_flip_coin (lib_rnd_t *ctx, u32 prob)
{
    return lib_rnd32 (ctx) < prob;
}

END_DECLS

#endif /* lib_rnd_h */