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
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 )
16 M: object random-bytes* ( n tuple -- byte-array )
17 [ random-32* ] curry replicate [ 4 >le ] map concat ;
19 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
21 ERROR: no-random-number-generator ;
23 M: no-random-number-generator summary
24 drop "Random number generator is not defined." ;
26 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
28 M: f random-32* ( obj -- * ) no-random-number-generator ;
30 : random-bytes ( n -- byte-array )
32 dup 3 mask zero? [ 1+ ] unless
33 random-generator get random-bytes*
36 : random ( seq -- elt )
39 length dup log2 7 + 8 /i 1+
40 [ random-bytes byte-array>bignum ]
41 [ 3 shift 2^ ] bi / * >integer
45 : delete-random ( seq -- elt )
46 [ length random ] keep [ nth ] 2keep delete-nth ;
48 : random-bits ( n -- r ) 2^ random ;
50 : with-random ( tuple quot -- )
51 random-generator swap with-variable ; inline
53 : with-system-random ( quot -- )
54 system-random-generator get swap with-random ; inline
56 : with-secure-random ( quot -- )
57 secure-random-generator get swap with-random ; inline