]> gitweb.factorcode.org Git - factor.git/blob - basis/random/random.factor
Merge branch 'master' of git://repo.or.cz/factor/jcg
[factor.git] / basis / random / random.factor
1 ! Copyright (C) 2008 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: alien.c-types kernel math namespaces sequences
4 io.backend io.binary combinators system vocabs.loader
5 summary math.bitwise ;
6 IN: random
7
8 SYMBOL: system-random-generator
9 SYMBOL: secure-random-generator
10 SYMBOL: random-generator
11
12 GENERIC: seed-random ( tuple seed -- )
13 GENERIC: random-32* ( tuple -- r )
14 GENERIC: random-bytes* ( n tuple -- byte-array )
15
16 M: object random-bytes* ( n tuple -- byte-array )
17     [ random-32* ] curry replicate [ 4 >le ] map concat ;
18
19 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
20
21 ERROR: no-random-number-generator ;
22
23 M: no-random-number-generator summary
24     drop "Random number generator is not defined." ;
25
26 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
27
28 M: f random-32* ( obj -- * ) no-random-number-generator ;
29
30 : random-bytes ( n -- byte-array )
31     [
32         dup 3 mask zero? [ 1+ ] unless
33         random-generator get random-bytes*
34     ] keep head ;
35
36 <PRIVATE
37
38 : random-integer ( n -- n' )
39     dup log2 7 + 8 /i 1+
40     [ random-bytes byte-array>bignum ]
41     [ 3 shift 2^ ] bi / * >integer ;
42
43 PRIVATE>
44
45 : random-bits ( n -- r ) 2^ random-integer ;
46
47 : random ( seq -- elt )
48     [ f ] [
49         [ length random-integer ] keep nth
50     ] if-empty ;
51
52 : delete-random ( seq -- elt )
53     [ length random-integer ] keep [ nth ] 2keep delete-nth ;
54
55 : with-random ( tuple quot -- )
56     random-generator swap with-variable ; inline
57
58 : with-system-random ( quot -- )
59     system-random-generator get swap with-random ; inline
60
61 : with-secure-random ( quot -- )
62     secure-random-generator get swap with-random ; inline