]> git.proxmox.com Git - ceph.git/blob - ceph/src/civetweb/src/third_party/duktape-1.8.0/src-separate/duk_util_tinyrandom.c
buildsys: switch source download to quincy
[ceph.git] / ceph / src / civetweb / src / third_party / duktape-1.8.0 / src-separate / duk_util_tinyrandom.c
1 /*
2 * A tiny random number generator.
3 *
4 * Currently used for Math.random().
5 *
6 * http://www.woodmann.com/forum/archive/index.php/t-3100.html
7 */
8
9 #include "duk_internal.h"
10
11 #define DUK__UPDATE_RND(rnd) do { \
12 (rnd) += ((rnd) * (rnd)) | 0x05; \
13 (rnd) = ((rnd) & 0xffffffffU); /* if duk_uint32_t is exactly 32 bits, this is a NOP */ \
14 } while (0)
15
16 #define DUK__RND_BIT(rnd) ((rnd) >> 31) /* only use the highest bit */
17
18 DUK_INTERNAL duk_uint32_t duk_util_tinyrandom_get_bits(duk_hthread *thr, duk_small_int_t n) {
19 duk_small_int_t i;
20 duk_uint32_t res = 0;
21 duk_uint32_t rnd;
22
23 rnd = thr->heap->rnd_state;
24
25 for (i = 0; i < n; i++) {
26 DUK__UPDATE_RND(rnd);
27 res <<= 1;
28 res += DUK__RND_BIT(rnd);
29 }
30
31 thr->heap->rnd_state = rnd;
32
33 return res;
34 }
35
36 DUK_INTERNAL duk_double_t duk_util_tinyrandom_get_double(duk_hthread *thr) {
37 duk_double_t t;
38 duk_small_int_t n;
39 duk_uint32_t rnd;
40
41 /*
42 * XXX: could make this a lot faster if we create the double memory
43 * representation directly. Feasible easily (must be uniform random).
44 */
45
46 rnd = thr->heap->rnd_state;
47
48 n = 53; /* enough to cover the whole mantissa */
49 t = 0.0;
50
51 do {
52 DUK__UPDATE_RND(rnd);
53 t += DUK__RND_BIT(rnd);
54 t /= 2.0;
55 } while (--n);
56
57 thr->heap->rnd_state = rnd;
58
59 DUK_ASSERT(t >= (duk_double_t) 0.0);
60 DUK_ASSERT(t < (duk_double_t) 1.0);
61
62 return t;
63 }