(index<- ) ./librand/reader.rs
git branch: * master 5200215 auto merge of #14035 : alexcrichton/rust/experimental, r=huonw
modified: Fri May 9 13:02:28 2014
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(vec!(1,2,3,4,5,6,7,8)));
27 /// println!("{:x}", rng.gen::<uint>());
28 /// ```
29 pub struct ReaderRng<R> {
30 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 #[allow(deprecated_owned_vector)]
72 mod test {
73 use super::ReaderRng;
74 use std::io::MemReader;
75 use std::cast;
76 use Rng;
77
78 #[test]
79 fn test_reader_rng_u64() {
80 // transmute from the target to avoid endianness concerns.
81 let v = box [1u64, 2u64, 3u64];
82 let bytes: ~[u8] = unsafe {cast::transmute(v)};
83 let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
84
85 assert_eq!(rng.next_u64(), 1);
86 assert_eq!(rng.next_u64(), 2);
87 assert_eq!(rng.next_u64(), 3);
88 }
89 #[test]
90 fn test_reader_rng_u32() {
91 // transmute from the target to avoid endianness concerns.
92 let v = box [1u32, 2u32, 3u32];
93 let bytes: ~[u8] = unsafe {cast::transmute(v)};
94 let mut rng = ReaderRng::new(MemReader::new(bytes.move_iter().collect()));
95
96 assert_eq!(rng.next_u32(), 1);
97 assert_eq!(rng.next_u32(), 2);
98 assert_eq!(rng.next_u32(), 3);
99 }
100 #[test]
101 fn test_reader_rng_fill_bytes() {
102 let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
103 let mut w = [0u8, .. 8];
104
105 let mut rng = ReaderRng::new(MemReader::new(Vec::from_slice(v)));
106 rng.fill_bytes(w);
107
108 assert!(v == w);
109 }
110
111 #[test]
112 #[should_fail]
113 fn test_reader_rng_insufficient_bytes() {
114 let mut rng = ReaderRng::new(MemReader::new(vec!()));
115 let mut v = [0u8, .. 3];
116 rng.fill_bytes(v);
117 }
118 }