]> gitweb.factorcode.org Git - factor.git/blob - basis/random/random.factor
Fix permission bits
[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 : random ( seq -- elt )
37     [ f ] [
38         [
39             length dup log2 7 + 8 /i 1+
40             [ random-bytes byte-array>bignum ]
41             [ 3 shift 2^ ] bi / * >integer
42         ] keep nth
43     ] if-empty ;
44
45 : delete-random ( seq -- elt )
46     [ length random ] keep [ nth ] 2keep delete-nth ;
47
48 : random-bits ( n -- r ) 2^ random ;
49
50 : with-random ( tuple quot -- )
51     random-generator swap with-variable ; inline
52
53 : with-system-random ( quot -- )
54     system-random-generator get swap with-random ; inline
55
56 : with-secure-random ( quot -- )
57     secure-random-generator get swap with-random ; inline