factor/extra/random/random.factor

40 lines
1010 B
Factor
Raw Normal View History

2008-03-19 17:18:03 -04:00
! Copyright (C) 2008 Doug Coleman.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
2008-03-19 17:18:03 -04:00
USING: alien.c-types kernel math namespaces sequences
io.backend ;
2007-09-20 18:09:08 -04:00
IN: random
2008-03-19 17:18:03 -04:00
HOOK: os-crypto-random-bytes io-backend ( n -- byte-array )
HOOK: os-random-bytes io-backend ( n -- byte-array )
HOOK: os-crypto-random-32 io-backend ( -- r )
HOOK: os-random-32 io-backend ( -- r )
2007-09-20 18:09:08 -04:00
2008-03-19 17:18:03 -04:00
GENERIC: seed-random ( tuple seed -- )
GENERIC: random-32 ( tuple -- r )
2007-09-20 18:09:08 -04:00
2008-03-19 17:18:03 -04:00
: (random-bytes) ( tuple n -- byte-array )
[ drop random-32 ] with map >c-uint-array ;
2007-09-20 18:09:08 -04:00
2008-03-19 22:41:39 -04:00
SYMBOL: random-generator
2007-09-20 18:09:08 -04:00
2008-03-19 17:18:03 -04:00
: random-bytes ( n -- r )
[
4 /mod zero? [ 1+ ] unless
2008-03-19 22:41:39 -04:00
random-generator get swap (random-bytes)
2008-03-19 17:18:03 -04:00
] keep head ;
2007-09-20 18:09:08 -04:00
: random ( seq -- elt )
dup empty? [
drop f
] [
[
2008-03-19 17:18:03 -04:00
length dup log2 7 + 8 /i
random-bytes byte-array>bignum swap mod
2007-09-20 18:09:08 -04:00
] keep nth
] if ;
2008-03-19 22:41:39 -04:00
: random-bits ( n -- r ) 2^ random ;
2008-03-19 17:18:03 -04:00
: with-random ( tuple quot -- )
2008-03-19 22:41:39 -04:00
random-generator swap with-variable ; inline