about summary refs log tree commit diff
path: root/src/libstd/rand
diff options
context:
space:
mode:
authorAlex Crichton <alex@alexcrichton.com>2015-04-09 17:42:22 -0700
committerAlex Crichton <alex@alexcrichton.com>2015-04-14 10:14:11 -0700
commitbf4e77d4b543632ca4df8fdd7092850dffc3954b (patch)
treec4b56d2a5974e1b3bf4bfc8b7ca1a62d64c2c341 /src/libstd/rand
parentdabf0c6371d3b193664f58746fa27c1835a010f3 (diff)
downloadrust-bf4e77d4b543632ca4df8fdd7092850dffc3954b.tar.gz
rust-bf4e77d4b543632ca4df8fdd7092850dffc3954b.zip
std: Remove old_io/old_path/rand modules
This commit entirely removes the old I/O, path, and rand modules. All
functionality has been deprecated and unstable for quite some time now!
Diffstat (limited to 'src/libstd/rand')
-rw-r--r--src/libstd/rand/mod.rs112
-rw-r--r--src/libstd/rand/os.rs25
-rw-r--r--src/libstd/rand/reader.rs56
3 files changed, 43 insertions, 150 deletions
diff --git a/src/libstd/rand/mod.rs b/src/libstd/rand/mod.rs
index fad57323d34..9800a252777 100644
--- a/src/libstd/rand/mod.rs
+++ b/src/libstd/rand/mod.rs
@@ -224,27 +224,22 @@
 //! ```
 
 #![unstable(feature = "rand")]
-#![deprecated(reason = "use the crates.io `rand` library instead",
-              since = "1.0.0-alpha")]
-#![allow(deprecated)]
+
+use prelude::v1::*;
 
 use cell::RefCell;
-use clone::Clone;
-use old_io::IoResult;
-use iter::Iterator;
+use io;
 use mem;
 use rc::Rc;
-use result::Result::{Ok, Err};
-use vec::Vec;
 
 #[cfg(target_pointer_width = "32")]
 use core_rand::IsaacRng as IsaacWordRng;
 #[cfg(target_pointer_width = "64")]
 use core_rand::Isaac64Rng as IsaacWordRng;
 
-pub use core_rand::{Rand, Rng, SeedableRng, Open01, Closed01};
-pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng, ChaChaRng};
-pub use core_rand::{distributions, reseeding};
+pub use core_rand::{Rand, Rng, SeedableRng};
+pub use core_rand::{XorShiftRng, IsaacRng, Isaac64Rng};
+pub use core_rand::reseeding;
 pub use rand::os::OsRng;
 
 pub mod os;
@@ -269,7 +264,7 @@ impl StdRng {
     ///
     /// Reading the randomness from the OS may fail, and any error is
     /// propagated via the `IoResult` return value.
-    pub fn new() -> IoResult<StdRng> {
+    pub fn new() -> io::Result<StdRng> {
         OsRng::new().map(|mut r| StdRng { rng: r.gen() })
     }
 }
@@ -298,22 +293,6 @@ impl<'a> SeedableRng<&'a [usize]> for StdRng {
     }
 }
 
-/// Create a weak random number generator with a default algorithm and seed.
-///
-/// It returns the fastest `Rng` algorithm currently available in Rust without
-/// consideration for cryptography or security. If you require a specifically
-/// seeded `Rng` for consistency over time you should pick one algorithm and
-/// create the `Rng` yourself.
-///
-/// This will read randomness from the operating system to seed the
-/// generator.
-pub fn weak_rng() -> XorShiftRng {
-    match OsRng::new() {
-        Ok(mut r) => r.gen(),
-        Err(e) => panic!("weak_rng: failed to create seeded RNG: {:?}", e)
-    }
-}
-
 /// Controls how the thread-local RNG is reseeded.
 struct ThreadRngReseeder;
 
@@ -376,83 +355,6 @@ impl Rng for ThreadRng {
     }
 }
 
-/// Generates a random value using the thread-local random number generator.
-///
-/// `random()` can generate various types of random things, and so may require
-/// type hinting to generate the specific type you want.
-///
-/// This function uses the thread local random number generator. This means
-/// that if you're calling `random()` in a loop, caching the generator can
-/// increase performance. An example is shown below.
-///
-/// # Examples
-///
-/// ```
-/// # #![feature(rand)]
-/// use std::rand;
-///
-/// let x: u8 = rand::random();
-/// println!("{}", 2 * x as u16);
-///
-/// let y = rand::random::<f64>();
-/// println!("{}", y);
-///
-/// if rand::random() { // generates a boolean
-///     println!("Better lucky than good!");
-/// }
-/// ```
-///
-/// Caching the thread local random number generator:
-///
-/// ```
-/// # #![feature(rand)]
-/// use std::rand;
-/// use std::rand::Rng;
-///
-/// let mut v = vec![1, 2, 3];
-///
-/// for x in v.iter_mut() {
-///     *x = rand::random()
-/// }
-///
-/// // would be faster as
-///
-/// let mut rng = rand::thread_rng();
-///
-/// for x in v.iter_mut() {
-///     *x = rng.gen();
-/// }
-/// ```
-#[inline]
-pub fn random<T: Rand>() -> T {
-    thread_rng().gen()
-}
-
-/// Randomly sample up to `amount` elements from an iterator.
-///
-/// # Examples
-///
-/// ```
-/// # #![feature(rand)]
-/// use std::rand::{thread_rng, sample};
-///
-/// let mut rng = thread_rng();
-/// let sample = sample(&mut rng, 1..100, 5);
-/// println!("{:?}", sample);
-/// ```
-pub fn sample<T, I: Iterator<Item=T>, R: Rng>(rng: &mut R,
-                                         mut iter: I,
-                                         amount: usize) -> Vec<T> {
-    let mut reservoir: Vec<T> = iter.by_ref().take(amount).collect();
-    for (i, elem) in iter.enumerate() {
-        let k = rng.gen_range(0, i + 1 + amount);
-        if k < amount {
-            reservoir[k] = elem;
-        }
-    }
-    return reservoir;
-}
-
 #[cfg(test)]
 mod test {
     use prelude::v1::*;
diff --git a/src/libstd/rand/os.rs b/src/libstd/rand/os.rs
index 38c57eec684..6c107590237 100644
--- a/src/libstd/rand/os.rs
+++ b/src/libstd/rand/os.rs
@@ -18,10 +18,10 @@ mod imp {
     use prelude::v1::*;
     use self::OsRngInner::*;
 
+    use fs::File;
+    use io;
     use libc;
     use mem;
-    use old_io::{IoResult, File};
-    use old_path::Path;
     use rand::Rng;
     use rand::reader::ReaderRng;
     use sys::os::errno;
@@ -147,12 +147,12 @@ mod imp {
 
     impl OsRng {
         /// Create a new `OsRng`.
-        pub fn new() -> IoResult<OsRng> {
+        pub fn new() -> io::Result<OsRng> {
             if is_getrandom_available() {
                 return Ok(OsRng { inner: OsGetrandomRng });
             }
 
-            let reader = try!(File::open(&Path::new("/dev/urandom")));
+            let reader = try!(File::open("/dev/urandom"));
             let reader_rng = ReaderRng::new(reader);
 
             Ok(OsRng { inner: OsReaderRng(reader_rng) })
@@ -186,7 +186,6 @@ mod imp {
     use prelude::v1::*;
 
     use io;
-    use old_io::IoResult;
     use mem;
     use rand::Rng;
     use libc::{c_int, size_t};
@@ -202,7 +201,8 @@ mod imp {
     ///
     /// This does not block.
     pub struct OsRng {
-        // dummy field to ensure that this struct cannot be constructed outside of this module
+        // dummy field to ensure that this struct cannot be constructed outside
+        // of this module
         _dummy: (),
     }
 
@@ -220,7 +220,7 @@ mod imp {
 
     impl OsRng {
         /// Create a new `OsRng`.
-        pub fn new() -> IoResult<OsRng> {
+        pub fn new() -> io::Result<OsRng> {
             Ok(OsRng { _dummy: () })
         }
     }
@@ -238,10 +238,12 @@ mod imp {
         }
         fn fill_bytes(&mut self, v: &mut [u8]) {
             let ret = unsafe {
-                SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t, v.as_mut_ptr())
+                SecRandomCopyBytes(kSecRandomDefault, v.len() as size_t,
+                                   v.as_mut_ptr())
             };
             if ret == -1 {
-                panic!("couldn't generate random bytes: {}", io::Error::last_os_error());
+                panic!("couldn't generate random bytes: {}",
+                       io::Error::last_os_error());
             }
         }
     }
@@ -253,7 +255,6 @@ mod imp {
 
     use io;
     use mem;
-    use old_io::{IoResult, IoError};
     use rand::Rng;
     use libc::types::os::arch::extra::{LONG_PTR};
     use libc::{DWORD, BYTE, LPCSTR, BOOL};
@@ -293,7 +294,7 @@ mod imp {
 
     impl OsRng {
         /// Create a new `OsRng`.
-        pub fn new() -> IoResult<OsRng> {
+        pub fn new() -> io::Result<OsRng> {
             let mut hcp = 0;
             let ret = unsafe {
                 CryptAcquireContextA(&mut hcp, 0 as LPCSTR, 0 as LPCSTR,
@@ -302,7 +303,7 @@ mod imp {
             };
 
             if ret == 0 {
-                Err(IoError::last_error())
+                Err(io::Error::last_os_error())
             } else {
                 Ok(OsRng { hcryptprov: hcp })
             }
diff --git a/src/libstd/rand/reader.rs b/src/libstd/rand/reader.rs
index ece6867ddca..3d0055b43c7 100644
--- a/src/libstd/rand/reader.rs
+++ b/src/libstd/rand/reader.rs
@@ -8,35 +8,26 @@
 // option. This file may not be copied, modified, or distributed
 // except according to those terms.
 
-//! A wrapper around any Reader to treat it as an RNG.
+//! A wrapper around any Read to treat it as an RNG.
 
-use old_io::Reader;
+#![allow(dead_code)]
+
+use prelude::v1::*;
+use io::prelude::*;
 use rand::Rng;
-use result::Result::{Ok, Err};
 
-/// An RNG that reads random bytes straight from a `Reader`. This will
+/// An RNG that reads random bytes straight from a `Read`. This will
 /// work best with an infinite reader, but this is not required.
 ///
 /// # Panics
 ///
 /// It will panic if it there is insufficient data to fulfill a request.
-///
-/// # Examples
-///
-/// ```
-/// # #![feature(rand, old_io)]
-/// use std::rand::{reader, Rng};
-/// use std::old_io::MemReader;
-///
-/// let mut rng = reader::ReaderRng::new(MemReader::new(vec!(1,2,3,4,5,6,7,8)));
-/// println!("{:x}", rng.gen::<usize>());
-/// ```
 pub struct ReaderRng<R> {
     reader: R
 }
 
-impl<R: Reader> ReaderRng<R> {
-    /// Create a new `ReaderRng` from a `Reader`.
+impl<R: Read> ReaderRng<R> {
+    /// Create a new `ReaderRng` from a `Read`.
     pub fn new(r: R) -> ReaderRng<R> {
         ReaderRng {
             reader: r
@@ -44,30 +35,29 @@ impl<R: Reader> ReaderRng<R> {
     }
 }
 
-impl<R: Reader> Rng for ReaderRng<R> {
+impl<R: Read> Rng for ReaderRng<R> {
     fn next_u32(&mut self) -> u32 {
         // This is designed for speed: reading a LE integer on a LE
         // platform just involves blitting the bytes into the memory
         // of the u32, similarly for BE on BE; avoiding byteswapping.
-        if cfg!(target_endian="little") {
-            self.reader.read_le_u32().unwrap()
-        } else {
-            self.reader.read_be_u32().unwrap()
-        }
+        let mut bytes = [0; 4];
+        self.fill_bytes(&mut bytes);
+        unsafe { *(bytes.as_ptr() as *const u32) }
     }
     fn next_u64(&mut self) -> u64 {
         // see above for explanation.
-        if cfg!(target_endian="little") {
-            self.reader.read_le_u64().unwrap()
-        } else {
-            self.reader.read_be_u64().unwrap()
-        }
+        let mut bytes = [0; 8];
+        self.fill_bytes(&mut bytes);
+        unsafe { *(bytes.as_ptr() as *const u64) }
     }
-    fn fill_bytes(&mut self, v: &mut [u8]) {
-        if v.len() == 0 { return }
-        match self.reader.read_at_least(v.len(), v) {
-            Ok(_) => {}
-            Err(e) => panic!("ReaderRng.fill_bytes error: {:?}", e)
+    fn fill_bytes(&mut self, mut v: &mut [u8]) {
+        while v.len() > 0 {
+            let t = v;
+            match self.reader.read(t) {
+                Ok(0) => panic!("ReaderRng.fill_bytes: EOF reached"),
+                Ok(n) => v = t.split_at_mut(n).1,
+                Err(e) => panic!("ReaderRng.fill_bytes: {}", e),
+            }
         }
     }
 }