summaryrefslogtreecommitdiff
path: root/shell/random.c
diff options
context:
space:
mode:
authorDenys Vlasenko <vda.linux@googlemail.com>2009-10-09 20:59:04 +0200
committerDenys Vlasenko <vda.linux@googlemail.com>2009-10-09 20:59:04 +0200
commit3ea2e82dc7b32703f5043c3b30b049905a0d07aa (patch)
treeeae992a986a4ce66efa32845ecccc204a0c4c0e1 /shell/random.c
parenta05b2b856bf095dfd5f575c106d1a9e5ac6edd3c (diff)
downloadbusybox-w32-3ea2e82dc7b32703f5043c3b30b049905a0d07aa.tar.gz
busybox-w32-3ea2e82dc7b32703f5043c3b30b049905a0d07aa.tar.bz2
busybox-w32-3ea2e82dc7b32703f5043c3b30b049905a0d07aa.zip
ash: factor out $RANDOM support
function old new delta next_random - 46 +46 ash_main 1361 1356 -5 change_random 132 97 -35 ------------------------------------------------------------------------------ (add/remove: 1/0 grow/shrink: 0/2 up/down: 46/-40) Total: 6 bytes Signed-off-by: Denys Vlasenko <vda.linux@googlemail.com>
Diffstat (limited to 'shell/random.c')
-rw-r--r--shell/random.c37
1 files changed, 37 insertions, 0 deletions
diff --git a/shell/random.c b/shell/random.c
new file mode 100644
index 000000000..a4dce846d
--- /dev/null
+++ b/shell/random.c
@@ -0,0 +1,37 @@
1/* vi: set sw=4 ts=4: */
2/*
3 * $RANDOM support.
4 *
5 * Copyright (C) 2008 Denys Vlasenko
6 *
7 * Licensed under GPLv2, see file LICENSE in this tarball for details.
8 */
9#include "libbb.h"
10#include "random.h"
11
12uint32_t FAST_FUNC
13next_random(random_t *rnd)
14{
15 /* Galois LFSR parameter */
16 /* Taps at 32 31 29 1: */
17 enum { MASK = 0x8000000b };
18 /* Another example - taps at 32 31 30 10: */
19 /* MASK = 0x00400007 */
20
21 uint32_t t;
22
23 /* LCG has period of 2^32 and alternating lowest bit */
24 rnd->LCG = 1664525 * rnd->LCG + 1013904223;
25 /* Galois LFSR has period of 2^32-1 = 3 * 5 * 17 * 257 * 65537 */
26 t = (rnd->galois_LFSR << 1);
27 if (rnd->galois_LFSR < 0) /* if we just shifted 1 out of msb... */
28 t ^= MASK;
29 rnd->galois_LFSR = t;
30 /* Both are weak, combining them gives better randomness
31 * and ~2^64 period. & 0x7fff is probably bash compat
32 * for $RANDOM range. Combining with subtraction is
33 * just for fun. + and ^ would work equally well. */
34 t = (t - rnd->LCG) & 0x7fff;
35
36 return t;
37}