]> git.lizzy.rs Git - rust.git/blob - src/librand/reader.rs
auto merge of #13049 : alexcrichton/rust/io-fill, r=huonw
[rust.git] / src / librand / reader.rs
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 Reader to treat it as an RNG.
12
13 use Rng;
14
15 /// An RNG that reads random bytes straight from a `Reader`. This will
16 /// work best with an infinite reader, but this is not required.
17 ///
18 /// It will fail if it there is insufficient data to fulfill a request.
19 ///
20 /// # Example
21 ///
22 /// ```rust
23 /// use rand::{reader, Rng};
24 /// use std::io::MemReader;
25 ///
26 /// let mut rng = reader::ReaderRng::new(MemReader::new(~[1,2,3,4,5,6,7,8]));
27 /// println!("{:x}", rng.gen::<uint>());
28 /// ```
29 pub struct ReaderRng<R> {
30     priv reader: R
31 }
32
33 impl<R: Reader> ReaderRng<R> {
34     /// Create a new `ReaderRng` from a `Reader`.
35     pub fn new(r: R) -> ReaderRng<R> {
36         ReaderRng {
37             reader: r
38         }
39     }
40 }
41
42 impl<R: Reader> Rng for ReaderRng<R> {
43     fn next_u32(&mut self) -> u32 {
44         // This is designed for speed: reading a LE integer on a LE
45         // platform just involves blitting the bytes into the memory
46         // of the u32, similarly for BE on BE; avoiding byteswapping.
47         if cfg!(target_endian="little") {
48             self.reader.read_le_u32().unwrap()
49         } else {
50             self.reader.read_be_u32().unwrap()
51         }
52     }
53     fn next_u64(&mut self) -> u64 {
54         // see above for explanation.
55         if cfg!(target_endian="little") {
56             self.reader.read_le_u64().unwrap()
57         } else {
58             self.reader.read_be_u64().unwrap()
59         }
60     }
61     fn fill_bytes(&mut self, v: &mut [u8]) {
62         if v.len() == 0 { return }
63         match self.reader.fill(v) {
64             Ok(()) => {}
65             Err(e) => fail!("ReaderRng.fill_bytes error: {}", e)
66         }
67     }
68 }
69
70 #[cfg(test)]
71 mod test {
72     use super::ReaderRng;
73     use std::io::MemReader;
74     use std::cast;
75     use Rng;
76
77     #[test]
78     fn test_reader_rng_u64() {
79         // transmute from the target to avoid endianness concerns.
80         let v = ~[1u64, 2u64, 3u64];
81         let bytes: ~[u8] = unsafe {cast::transmute(v)};
82         let mut rng = ReaderRng::new(MemReader::new(bytes));
83
84         assert_eq!(rng.next_u64(), 1);
85         assert_eq!(rng.next_u64(), 2);
86         assert_eq!(rng.next_u64(), 3);
87     }
88     #[test]
89     fn test_reader_rng_u32() {
90         // transmute from the target to avoid endianness concerns.
91         let v = ~[1u32, 2u32, 3u32];
92         let bytes: ~[u8] = unsafe {cast::transmute(v)};
93         let mut rng = ReaderRng::new(MemReader::new(bytes));
94
95         assert_eq!(rng.next_u32(), 1);
96         assert_eq!(rng.next_u32(), 2);
97         assert_eq!(rng.next_u32(), 3);
98     }
99     #[test]
100     fn test_reader_rng_fill_bytes() {
101         let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
102         let mut w = [0u8, .. 8];
103
104         let mut rng = ReaderRng::new(MemReader::new(v.to_owned()));
105         rng.fill_bytes(w);
106
107         assert!(v == w);
108     }
109
110     #[test]
111     #[should_fail]
112     fn test_reader_rng_insufficient_bytes() {
113         let mut rng = ReaderRng::new(MemReader::new(~[]));
114         let mut v = [0u8, .. 3];
115         rng.fill_bytes(v);
116     }
117 }