2014-05-30 11:07:16 -05:00
|
|
|
// Copyright 2013-2014 The Rust Project Developers. See the COPYRIGHT
|
2013-09-22 05:51:57 -05:00
|
|
|
// file at the top-level directory of this distribution and at
|
|
|
|
// http://rust-lang.org/COPYRIGHT.
|
|
|
|
//
|
|
|
|
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
|
|
|
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
|
|
|
|
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
|
|
|
|
// option. This file may not be copied, modified, or distributed
|
|
|
|
// except according to those terms.
|
|
|
|
|
|
|
|
//! Interfaces to the operating system provided random number
|
|
|
|
//! generators.
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
pub use self::imp::OsRng;
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-05-05 02:07:49 -05:00
|
|
|
#[cfg(unix, not(target_os = "ios"))]
|
2014-03-19 19:53:57 -05:00
|
|
|
mod imp {
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
use io::{IoResult, File};
|
|
|
|
use path::Path;
|
|
|
|
use rand::Rng;
|
|
|
|
use rand::reader::ReaderRng;
|
|
|
|
use result::{Ok, Err};
|
2014-03-19 19:53:57 -05:00
|
|
|
|
|
|
|
/// A random number generator that retrieves randomness straight from
|
|
|
|
/// the operating system. Platform sources:
|
|
|
|
///
|
|
|
|
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
|
|
|
|
/// `/dev/urandom`.
|
|
|
|
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
|
|
|
|
/// service provider with the `PROV_RSA_FULL` type.
|
2014-05-05 02:07:49 -05:00
|
|
|
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
|
2014-03-19 19:53:57 -05:00
|
|
|
/// This does not block.
|
2013-09-22 05:51:57 -05:00
|
|
|
#[cfg(unix)]
|
2014-05-29 23:37:31 -05:00
|
|
|
pub struct OsRng {
|
2014-03-27 17:10:38 -05:00
|
|
|
inner: ReaderRng<File>
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl OsRng {
|
|
|
|
/// Create a new `OsRng`.
|
|
|
|
pub fn new() -> IoResult<OsRng> {
|
2014-03-24 08:41:43 -05:00
|
|
|
let reader = try!(File::open(&Path::new("/dev/urandom")));
|
2014-03-19 19:53:57 -05:00
|
|
|
let reader_rng = ReaderRng::new(reader);
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
Ok(OsRng { inner: reader_rng })
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Rng for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn next_u32(&mut self) -> u32 {
|
|
|
|
self.inner.next_u32()
|
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
|
|
|
self.inner.next_u64()
|
|
|
|
}
|
|
|
|
fn fill_bytes(&mut self, v: &mut [u8]) {
|
|
|
|
self.inner.fill_bytes(v)
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-05-05 02:07:49 -05:00
|
|
|
#[cfg(target_os = "ios")]
|
|
|
|
mod imp {
|
|
|
|
extern crate libc;
|
|
|
|
|
|
|
|
use collections::Collection;
|
|
|
|
use io::{IoResult};
|
|
|
|
use kinds::marker;
|
|
|
|
use mem;
|
|
|
|
use os;
|
|
|
|
use rand::Rng;
|
|
|
|
use result::{Ok};
|
|
|
|
use self::libc::{c_int, size_t};
|
2014-08-06 20:58:43 -05:00
|
|
|
use slice::MutableSlice;
|
2014-05-05 02:07:49 -05:00
|
|
|
|
|
|
|
/// A random number generator that retrieves randomness straight from
|
|
|
|
/// the operating system. Platform sources:
|
|
|
|
///
|
|
|
|
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
|
|
|
|
/// `/dev/urandom`.
|
|
|
|
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
|
|
|
|
/// service provider with the `PROV_RSA_FULL` type.
|
|
|
|
/// - iOS: calls SecRandomCopyBytes as /dev/(u)random is sandboxed
|
|
|
|
/// This does not block.
|
|
|
|
pub struct OsRng {
|
|
|
|
marker: marker::NoCopy
|
|
|
|
}
|
|
|
|
|
2014-08-25 05:45:07 -05:00
|
|
|
#[repr(C)]
|
2014-05-05 02:07:49 -05:00
|
|
|
struct SecRandom;
|
|
|
|
|
2014-06-25 14:47:34 -05:00
|
|
|
static kSecRandomDefault: *const SecRandom = 0 as *const SecRandom;
|
2014-05-05 02:07:49 -05:00
|
|
|
|
|
|
|
#[link(name = "Security", kind = "framework")]
|
|
|
|
extern "C" {
|
2014-06-25 14:47:34 -05:00
|
|
|
fn SecRandomCopyBytes(rnd: *const SecRandom,
|
|
|
|
count: size_t, bytes: *mut u8) -> c_int;
|
2014-05-05 02:07:49 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
impl OsRng {
|
|
|
|
/// Create a new `OsRng`.
|
|
|
|
pub fn new() -> IoResult<OsRng> {
|
|
|
|
Ok(OsRng {marker: marker::NoCopy} )
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Rng for OsRng {
|
|
|
|
fn next_u32(&mut self) -> u32 {
|
|
|
|
let mut v = [0u8, .. 4];
|
|
|
|
self.fill_bytes(v);
|
|
|
|
unsafe { mem::transmute(v) }
|
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
|
|
|
let mut v = [0u8, .. 8];
|
|
|
|
self.fill_bytes(v);
|
|
|
|
unsafe { mem::transmute(v) }
|
|
|
|
}
|
|
|
|
fn fill_bytes(&mut self, v: &mut [u8]) {
|
|
|
|
let ret = unsafe {
|
|
|
|
SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
|
|
|
|
};
|
|
|
|
if ret == -1 {
|
|
|
|
fail!("couldn't generate random bytes: {}", os::last_os_error());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2013-09-22 05:51:57 -05:00
|
|
|
#[cfg(windows)]
|
2014-03-19 19:53:57 -05:00
|
|
|
mod imp {
|
2014-02-26 11:58:41 -06:00
|
|
|
extern crate libc;
|
|
|
|
|
2014-06-06 18:33:44 -05:00
|
|
|
use core_collections::Collection;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
use io::{IoResult, IoError};
|
|
|
|
use mem;
|
|
|
|
use ops::Drop;
|
|
|
|
use os;
|
|
|
|
use rand::Rng;
|
|
|
|
use result::{Ok, Err};
|
|
|
|
use rt::stack;
|
2014-07-28 15:35:34 -05:00
|
|
|
use self::libc::{DWORD, BYTE, LPCSTR, BOOL};
|
|
|
|
use self::libc::types::os::arch::extra::{LONG_PTR};
|
2014-08-06 20:58:43 -05:00
|
|
|
use slice::MutableSlice;
|
2014-03-19 19:53:57 -05:00
|
|
|
|
2014-07-28 15:35:34 -05:00
|
|
|
type HCRYPTPROV = LONG_PTR;
|
2014-03-19 19:53:57 -05:00
|
|
|
|
|
|
|
/// A random number generator that retrieves randomness straight from
|
|
|
|
/// the operating system. Platform sources:
|
|
|
|
///
|
|
|
|
/// - Unix-like systems (Linux, Android, Mac OSX): read directly from
|
|
|
|
/// `/dev/urandom`.
|
|
|
|
/// - Windows: calls `CryptGenRandom`, using the default cryptographic
|
|
|
|
/// service provider with the `PROV_RSA_FULL` type.
|
|
|
|
///
|
|
|
|
/// This does not block.
|
2014-05-29 23:37:31 -05:00
|
|
|
pub struct OsRng {
|
2014-03-27 17:10:38 -05:00
|
|
|
hcryptprov: HCRYPTPROV
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
2013-10-01 11:18:57 -05:00
|
|
|
|
2014-03-19 19:53:57 -05:00
|
|
|
static PROV_RSA_FULL: DWORD = 1;
|
|
|
|
static CRYPT_SILENT: DWORD = 64;
|
|
|
|
static CRYPT_VERIFYCONTEXT: DWORD = 0xF0000000;
|
2014-03-21 13:51:11 -05:00
|
|
|
static NTE_BAD_SIGNATURE: DWORD = 0x80090006;
|
2014-03-19 19:53:57 -05:00
|
|
|
|
2014-05-30 11:07:16 -05:00
|
|
|
#[allow(non_snake_case_functions)]
|
2014-03-19 19:53:57 -05:00
|
|
|
extern "system" {
|
|
|
|
fn CryptAcquireContextA(phProv: *mut HCRYPTPROV,
|
|
|
|
pszContainer: LPCSTR,
|
|
|
|
pszProvider: LPCSTR,
|
|
|
|
dwProvType: DWORD,
|
|
|
|
dwFlags: DWORD) -> BOOL;
|
|
|
|
fn CryptGenRandom(hProv: HCRYPTPROV,
|
|
|
|
dwLen: DWORD,
|
|
|
|
pbBuffer: *mut BYTE) -> BOOL;
|
|
|
|
fn CryptReleaseContext(hProv: HCRYPTPROV, dwFlags: DWORD) -> BOOL;
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl OsRng {
|
|
|
|
/// Create a new `OsRng`.
|
|
|
|
pub fn new() -> IoResult<OsRng> {
|
2014-03-19 19:53:57 -05:00
|
|
|
let mut hcp = 0;
|
2014-03-21 13:51:11 -05:00
|
|
|
let mut ret = unsafe {
|
2014-03-19 19:53:57 -05:00
|
|
|
CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
|
|
|
|
PROV_RSA_FULL,
|
|
|
|
CRYPT_VERIFYCONTEXT | CRYPT_SILENT)
|
|
|
|
};
|
2014-03-21 13:51:11 -05:00
|
|
|
|
2014-04-28 04:09:20 -05:00
|
|
|
// FIXME #13259:
|
2014-03-21 13:51:11 -05:00
|
|
|
// It turns out that if we can't acquire a context with the
|
|
|
|
// NTE_BAD_SIGNATURE error code, the documentation states:
|
|
|
|
//
|
|
|
|
// The provider DLL signature could not be verified. Either the
|
|
|
|
// DLL or the digital signature has been tampered with.
|
|
|
|
//
|
|
|
|
// Sounds fishy, no? As it turns out, our signature can be bad
|
|
|
|
// because our Thread Information Block (TIB) isn't exactly what it
|
|
|
|
// expects. As to why, I have no idea. The only data we store in the
|
|
|
|
// TIB is the stack limit for each thread, but apparently that's
|
|
|
|
// enough to make the signature valid.
|
|
|
|
//
|
|
|
|
// Furthermore, this error only happens the *first* time we call
|
|
|
|
// CryptAcquireContext, so we don't have to worry about future
|
|
|
|
// calls.
|
|
|
|
//
|
|
|
|
// Anyway, the fix employed here is that if we see this error, we
|
|
|
|
// pray that we're not close to the end of the stack, temporarily
|
|
|
|
// set the stack limit to 0 (what the TIB originally was), acquire a
|
|
|
|
// context, and then reset the stack limit.
|
|
|
|
//
|
|
|
|
// Again, I'm not sure why this is the fix, nor why we're getting
|
|
|
|
// this error. All I can say is that this seems to allow libnative
|
|
|
|
// to progress where it otherwise would be hindered. Who knew?
|
|
|
|
if ret == 0 && os::errno() as DWORD == NTE_BAD_SIGNATURE {
|
|
|
|
unsafe {
|
|
|
|
let limit = stack::get_sp_limit();
|
|
|
|
stack::record_sp_limit(0);
|
|
|
|
ret = CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
|
|
|
|
PROV_RSA_FULL,
|
|
|
|
CRYPT_VERIFYCONTEXT | CRYPT_SILENT);
|
|
|
|
stack::record_sp_limit(limit);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2014-03-19 19:53:57 -05:00
|
|
|
if ret == 0 {
|
2014-03-24 08:41:43 -05:00
|
|
|
Err(IoError::last_error())
|
|
|
|
} else {
|
2014-05-29 23:37:31 -05:00
|
|
|
Ok(OsRng { hcryptprov: hcp })
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Rng for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn next_u32(&mut self) -> u32 {
|
|
|
|
let mut v = [0u8, .. 4];
|
|
|
|
self.fill_bytes(v);
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
unsafe { mem::transmute(v) }
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
fn next_u64(&mut self) -> u64 {
|
|
|
|
let mut v = [0u8, .. 8];
|
|
|
|
self.fill_bytes(v);
|
core: Remove the cast module
This commit revisits the `cast` module in libcore and libstd, and scrutinizes
all functions inside of it. The result was to remove the `cast` module entirely,
folding all functionality into the `mem` module. Specifically, this is the fate
of each function in the `cast` module.
* transmute - This function was moved to `mem`, but it is now marked as
#[unstable]. This is due to planned changes to the `transmute`
function and how it can be invoked (see the #[unstable] comment).
For more information, see RFC 5 and #12898
* transmute_copy - This function was moved to `mem`, with clarification that is
is not an error to invoke it with T/U that are different
sizes, but rather that it is strongly discouraged. This
function is now #[stable]
* forget - This function was moved to `mem` and marked #[stable]
* bump_box_refcount - This function was removed due to the deprecation of
managed boxes as well as its questionable utility.
* transmute_mut - This function was previously deprecated, and removed as part
of this commit.
* transmute_mut_unsafe - This function doesn't serve much of a purpose when it
can be achieved with an `as` in safe code, so it was
removed.
* transmute_lifetime - This function was removed because it is likely a strong
indication that code is incorrect in the first place.
* transmute_mut_lifetime - This function was removed for the same reasons as
`transmute_lifetime`
* copy_lifetime - This function was moved to `mem`, but it is marked
`#[unstable]` now due to the likelihood of being removed in
the future if it is found to not be very useful.
* copy_mut_lifetime - This function was also moved to `mem`, but had the same
treatment as `copy_lifetime`.
* copy_lifetime_vec - This function was removed because it is not used today,
and its existence is not necessary with DST
(copy_lifetime will suffice).
In summary, the cast module was stripped down to these functions, and then the
functions were moved to the `mem` module.
transmute - #[unstable]
transmute_copy - #[stable]
forget - #[stable]
copy_lifetime - #[unstable]
copy_mut_lifetime - #[unstable]
[breaking-change]
2014-05-09 12:34:51 -05:00
|
|
|
unsafe { mem::transmute(v) }
|
2014-03-19 19:53:57 -05:00
|
|
|
}
|
|
|
|
fn fill_bytes(&mut self, v: &mut [u8]) {
|
|
|
|
let ret = unsafe {
|
|
|
|
CryptGenRandom(self.hcryptprov, v.len() as DWORD,
|
|
|
|
v.as_mut_ptr())
|
|
|
|
};
|
|
|
|
if ret == 0 {
|
|
|
|
fail!("couldn't generate random bytes: {}", os::last_os_error());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
impl Drop for OsRng {
|
2014-03-19 19:53:57 -05:00
|
|
|
fn drop(&mut self) {
|
|
|
|
let ret = unsafe {
|
|
|
|
CryptReleaseContext(self.hcryptprov, 0)
|
|
|
|
};
|
|
|
|
if ret == 0 {
|
|
|
|
fail!("couldn't release context: {}", os::last_os_error());
|
|
|
|
}
|
|
|
|
}
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[cfg(test)]
|
|
|
|
mod test {
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
use prelude::*;
|
|
|
|
|
2014-05-29 23:37:31 -05:00
|
|
|
use super::OsRng;
|
std: Recreate a `rand` module
This commit shuffles around some of the `rand` code, along with some
reorganization. The new state of the world is as follows:
* The librand crate now only depends on libcore. This interface is experimental.
* The standard library has a new module, `std::rand`. This interface will
eventually become stable.
Unfortunately, this entailed more of a breaking change than just shuffling some
names around. The following breaking changes were made to the rand library:
* Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which
will return an infinite stream of random values. Previous behavior can be
regained with `rng.gen_iter().take(n).collect()`
* Rng::gen_ascii_str() was removed. This has been replaced with
Rng::gen_ascii_chars() which will return an infinite stream of random ascii
characters. Similarly to gen_iter(), previous behavior can be emulated with
`rng.gen_ascii_chars().take(n).collect()`
* {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all
relied on being able to use an OSRng for seeding, but this is no longer
available in librand (where these types are defined). To retain the same
functionality, these types now implement the `Rand` trait so they can be
generated with a random seed from another random number generator. This allows
the stdlib to use an OSRng to create seeded instances of these RNGs.
* Rand implementations for `Box<T>` and `@T` were removed. These seemed to be
pretty rare in the codebase, and it allows for librand to not depend on
liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not
supported. If this is undesirable, librand can depend on liballoc and regain
these implementations.
* The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`,
but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice
structure now has a lifetime associated with it.
* The `sample` method on `Rng` has been moved to a top-level function in the
`rand` module due to its dependence on `Vec`.
cc #13851
[breaking-change]
2014-05-25 03:39:37 -05:00
|
|
|
use rand::Rng;
|
|
|
|
use task;
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_os_rng() {
|
2014-05-29 23:37:31 -05:00
|
|
|
let mut r = OsRng::new().unwrap();
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
r.next_u32();
|
|
|
|
r.next_u64();
|
|
|
|
|
|
|
|
let mut v = [0u8, .. 1000];
|
|
|
|
r.fill_bytes(v);
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
fn test_os_rng_tasks() {
|
|
|
|
|
2014-03-27 07:00:46 -05:00
|
|
|
let mut txs = vec!();
|
2014-04-21 16:58:52 -05:00
|
|
|
for _ in range(0u, 20) {
|
2014-03-09 16:58:32 -05:00
|
|
|
let (tx, rx) = channel();
|
|
|
|
txs.push(tx);
|
2014-01-26 21:42:26 -06:00
|
|
|
task::spawn(proc() {
|
2013-09-22 05:51:57 -05:00
|
|
|
// wait until all the tasks are ready to go.
|
2014-03-09 16:58:32 -05:00
|
|
|
rx.recv();
|
2013-09-22 05:51:57 -05:00
|
|
|
|
|
|
|
// deschedule to attempt to interleave things as much
|
|
|
|
// as possible (XXX: is this a good test?)
|
2014-05-29 23:37:31 -05:00
|
|
|
let mut r = OsRng::new().unwrap();
|
2013-09-22 05:51:57 -05:00
|
|
|
task::deschedule();
|
|
|
|
let mut v = [0u8, .. 1000];
|
|
|
|
|
2014-04-21 16:58:52 -05:00
|
|
|
for _ in range(0u, 100) {
|
2013-09-22 05:51:57 -05:00
|
|
|
r.next_u32();
|
|
|
|
task::deschedule();
|
|
|
|
r.next_u64();
|
|
|
|
task::deschedule();
|
|
|
|
r.fill_bytes(v);
|
|
|
|
task::deschedule();
|
|
|
|
}
|
2014-01-26 21:42:26 -06:00
|
|
|
})
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
// start all the tasks
|
2014-03-09 16:58:32 -05:00
|
|
|
for tx in txs.iter() {
|
|
|
|
tx.send(())
|
2013-09-22 05:51:57 -05:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|