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 byte-vectors fry byte-arrays ;
8 SYMBOL: system-random-generator
9 SYMBOL: secure-random-generator
10 SYMBOL: random-generator
12 GENERIC: seed-random ( tuple seed -- )
13 GENERIC: random-32* ( tuple -- r )
14 GENERIC: random-bytes* ( n tuple -- byte-array )
18 : adjust-random ( n m -- n' )
19 3 mask zero? [ 1+ ] unless ; inline
23 M: object random-bytes* ( n tuple -- byte-array )
24 [ [ 4 /i ] keep adjust-random ] dip
25 over 4 * <byte-vector>
26 [ '[ _ random-32* 4 >le _ push-all ] times ] keep ;
28 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
30 ERROR: no-random-number-generator ;
32 M: no-random-number-generator summary
33 drop "Random number generator is not defined." ;
35 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
37 M: f random-32* ( obj -- * ) no-random-number-generator ;
39 : random-bytes ( n -- byte-array )
41 dup adjust-random random-generator get random-bytes*
42 ] keep head-slice >byte-array ;
46 : random-integer ( n -- n' )
48 [ random-bytes byte-array>bignum ]
49 [ 3 shift 2^ ] bi / * >integer ;
53 : random-bits ( n -- r ) 2^ random-integer ;
55 : random ( seq -- elt )
57 [ length random-integer ] keep nth
60 : delete-random ( seq -- elt )
61 [ length random-integer ] keep [ nth ] 2keep delete-nth ;
63 : with-random ( tuple quot -- )
64 random-generator swap with-variable ; inline
66 : with-system-random ( quot -- )
67 system-random-generator get swap with-random ; inline
69 : with-secure-random ( quot -- )
70 secure-random-generator get swap with-random ; inline
75 { [ os windows? ] [ "random.windows" require ] }
76 { [ os unix? ] [ "random.unix" require ] }
79 "random.mersenne-twister" require