1 // Copyright 2013 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10 
11 //! A wrapper around any Read to treat it as an RNG.
12 
13 use std::io::{self, Read};
14 use std::mem;
15 use Rng;
16 
17 /// An RNG that reads random bytes straight from a `Read`. This will
18 /// work best with an infinite reader, but this is not required.
19 ///
20 /// # Panics
21 ///
22 /// It will panic if it there is insufficient data to fulfill a request.
23 ///
24 /// # Example
25 ///
26 /// ```rust
27 /// use rand::{read, Rng};
28 ///
29 /// let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
30 /// let mut rng = read::ReadRng::new(&data[..]);
31 /// println!("{:x}", rng.gen::<u32>());
32 /// ```
33 #[derive(Debug)]
34 pub struct ReadRng<R> {
35     reader: R
36 }
37 
38 impl<R: Read> ReadRng<R> {
39     /// Create a new `ReadRng` from a `Read`.
new(r: R) -> ReadRng<R>40     pub fn new(r: R) -> ReadRng<R> {
41         ReadRng {
42             reader: r
43         }
44     }
45 }
46 
47 impl<R: Read> Rng for ReadRng<R> {
next_u32(&mut self) -> u3248     fn next_u32(&mut self) -> u32 {
49         // This is designed for speed: reading a LE integer on a LE
50         // platform just involves blitting the bytes into the memory
51         // of the u32, similarly for BE on BE; avoiding byteswapping.
52         let mut buf = [0; 4];
53         fill(&mut self.reader, &mut buf).unwrap();
54         unsafe { *(buf.as_ptr() as *const u32) }
55     }
next_u64(&mut self) -> u6456     fn next_u64(&mut self) -> u64 {
57         // see above for explanation.
58         let mut buf = [0; 8];
59         fill(&mut self.reader, &mut buf).unwrap();
60         unsafe { *(buf.as_ptr() as *const u64) }
61     }
fill_bytes(&mut self, v: &mut [u8])62     fn fill_bytes(&mut self, v: &mut [u8]) {
63         if v.len() == 0 { return }
64         fill(&mut self.reader, v).unwrap();
65     }
66 }
67 
fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()>68 fn fill(r: &mut Read, mut buf: &mut [u8]) -> io::Result<()> {
69     while buf.len() > 0 {
70         match try!(r.read(buf)) {
71             0 => return Err(io::Error::new(io::ErrorKind::Other,
72                                            "end of file reached")),
73             n => buf = &mut mem::replace(&mut buf, &mut [])[n..],
74         }
75     }
76     Ok(())
77 }
78 
79 #[cfg(test)]
80 mod test {
81     use super::ReadRng;
82     use Rng;
83 
84     #[test]
test_reader_rng_u64()85     fn test_reader_rng_u64() {
86         // transmute from the target to avoid endianness concerns.
87         let v = vec![0u8, 0, 0, 0, 0, 0, 0, 1,
88                      0  , 0, 0, 0, 0, 0, 0, 2,
89                      0,   0, 0, 0, 0, 0, 0, 3];
90         let mut rng = ReadRng::new(&v[..]);
91 
92         assert_eq!(rng.next_u64(), 1_u64.to_be());
93         assert_eq!(rng.next_u64(), 2_u64.to_be());
94         assert_eq!(rng.next_u64(), 3_u64.to_be());
95     }
96     #[test]
test_reader_rng_u32()97     fn test_reader_rng_u32() {
98         let v = vec![0u8, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3];
99         let mut rng = ReadRng::new(&v[..]);
100 
101         assert_eq!(rng.next_u32(), 1_u32.to_be());
102         assert_eq!(rng.next_u32(), 2_u32.to_be());
103         assert_eq!(rng.next_u32(), 3_u32.to_be());
104     }
105     #[test]
test_reader_rng_fill_bytes()106     fn test_reader_rng_fill_bytes() {
107         let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
108         let mut w = [0u8; 8];
109 
110         let mut rng = ReadRng::new(&v[..]);
111         rng.fill_bytes(&mut w);
112 
113         assert!(v == w);
114     }
115 
116     #[test]
117     #[should_panic]
test_reader_rng_insufficient_bytes()118     fn test_reader_rng_insufficient_bytes() {
119         let mut rng = ReadRng::new(&[][..]);
120         let mut v = [0u8; 3];
121         rng.fill_bytes(&mut v);
122     }
123 }
124