2011-10-26 16:24:31 -07:00
|
|
|
/*
|
|
|
|
|
Module: rand
|
2011-06-15 11:19:50 -07:00
|
|
|
|
2011-10-26 16:24:31 -07:00
|
|
|
Random number generation
|
|
|
|
|
*/
|
2011-11-16 22:49:38 -06:00
|
|
|
#[abi = "cdecl"]
|
|
|
|
|
native mod rustrt {
|
2010-09-22 15:44:13 -07:00
|
|
|
type rctx;
|
|
|
|
|
fn rand_new() -> rctx;
|
2011-07-27 14:19:39 +02:00
|
|
|
fn rand_next(c: rctx) -> u32;
|
|
|
|
|
fn rand_free(c: rctx);
|
2010-07-25 21:45:09 -07:00
|
|
|
}
|
|
|
|
|
|
2011-10-26 16:24:31 -07:00
|
|
|
/* Section: Types */
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
Obj: rng
|
|
|
|
|
|
|
|
|
|
A random number generator
|
|
|
|
|
*/
|
|
|
|
|
type rng = obj {
|
|
|
|
|
/*
|
|
|
|
|
Method: next
|
|
|
|
|
|
|
|
|
|
Return the next random integer
|
|
|
|
|
*/
|
|
|
|
|
fn next() -> u32;
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
Method: next_float
|
|
|
|
|
|
|
|
|
|
Return the next random float
|
|
|
|
|
*/
|
|
|
|
|
fn next_float() -> float;
|
|
|
|
|
};
|
2011-07-29 13:31:44 +02:00
|
|
|
|
2011-08-19 15:16:48 -07:00
|
|
|
resource rand_res(c: rustrt::rctx) { rustrt::rand_free(c); }
|
2010-07-25 21:45:09 -07:00
|
|
|
|
2011-10-26 16:24:31 -07:00
|
|
|
/* Section: Operations */
|
|
|
|
|
|
|
|
|
|
/*
|
|
|
|
|
Function: mk_rng
|
|
|
|
|
|
|
|
|
|
Create a random number generator
|
|
|
|
|
*/
|
2010-07-25 21:45:09 -07:00
|
|
|
fn mk_rng() -> rng {
|
2011-07-29 13:31:44 +02:00
|
|
|
obj rt_rng(c: @rand_res) {
|
2011-08-19 15:16:48 -07:00
|
|
|
fn next() -> u32 { ret rustrt::rand_next(**c); }
|
2011-10-17 14:44:29 +02:00
|
|
|
fn next_float() -> float {
|
|
|
|
|
let u1 = rustrt::rand_next(**c) as float;
|
|
|
|
|
let u2 = rustrt::rand_next(**c) as float;
|
|
|
|
|
let u3 = rustrt::rand_next(**c) as float;
|
2011-11-16 02:10:43 +01:00
|
|
|
let scale = u32::max_value as float;
|
2011-10-17 14:44:29 +02:00
|
|
|
ret ((u1 / scale + u2) / scale + u3) / scale;
|
|
|
|
|
}
|
2010-07-25 21:45:09 -07:00
|
|
|
}
|
2011-07-29 13:31:44 +02:00
|
|
|
ret rt_rng(@rand_res(rustrt::rand_new()));
|
2010-07-25 21:45:09 -07:00
|
|
|
}
|
2010-09-22 15:44:13 -07:00
|
|
|
// Local Variables:
|
|
|
|
|
// mode: rust;
|
|
|
|
|
// fill-column: 78;
|
|
|
|
|
// indent-tabs-mode: nil
|
|
|
|
|
// c-basic-offset: 4
|
|
|
|
|
// buffer-file-coding-system: utf-8-unix
|
|
|
|
|
// End:
|