]> gitweb.factorcode.org Git - factor.git/blob - basis/random/random.factor
slightly faster
[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 byte-vectors fry byte-arrays ;
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 <PRIVATE
17
18 : adjust-random ( n m -- n' )
19     3 mask zero? [ 1+ ] unless ; inline
20
21 PRIVATE>
22
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 ;
27
28 M: object random-32* ( tuple -- r ) 4 random-bytes* le> ;
29
30 ERROR: no-random-number-generator ;
31
32 M: no-random-number-generator summary
33     drop "Random number generator is not defined." ;
34
35 M: f random-bytes* ( n obj -- * ) no-random-number-generator ;
36
37 M: f random-32* ( obj -- * ) no-random-number-generator ;
38
39 : random-bytes ( n -- byte-array )
40     [
41         dup adjust-random random-generator get random-bytes*
42     ] keep head-slice >byte-array ;
43
44 <PRIVATE
45
46 : random-integer ( n -- n' )
47     dup log2 7 + 8 /i 1+
48     [ random-bytes byte-array>bignum ]
49     [ 3 shift 2^ ] bi / * >integer ;
50
51 PRIVATE>
52
53 : random-bits ( n -- r ) 2^ random-integer ;
54
55 : random ( seq -- elt )
56     [ f ] [
57         [ length random-integer ] keep nth
58     ] if-empty ;
59
60 : delete-random ( seq -- elt )
61     [ length random-integer ] keep [ nth ] 2keep delete-nth ;
62
63 : with-random ( tuple quot -- )
64     random-generator swap with-variable ; inline
65
66 : with-system-random ( quot -- )
67     system-random-generator get swap with-random ; inline
68
69 : with-secure-random ( quot -- )
70     secure-random-generator get swap with-random ; inline
71
72 USE: vocabs.loader
73
74 {
75     { [ os windows? ] [ "random.windows" require ] }
76     { [ os unix? ] [ "random.unix" require ] }
77 } cond
78
79 "random.mersenne-twister" require