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 swap [ drop random-32* ] with map >c-uint-array ;
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 4 rem zero? [ 1+ ] unless
33 random-generator get random-bytes*
36 : random ( seq -- elt )
41 length dup log2 7 + 8 /i
42 random-bytes byte-array>bignum swap mod
46 : delete-random ( seq -- elt )
47 [ length random ] keep [ nth ] 2keep delete-nth ;
49 : random-bits ( n -- r ) 2^ random ;
51 : with-random ( tuple quot -- )
52 random-generator swap with-variable ; inline
54 : with-system-random ( quot -- )
55 system-random-generator get swap with-random ; inline
57 : with-secure-random ( quot -- )
58 secure-random-generator get swap with-random ; inline