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.
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.
11 //! A wrapper around any Reader to treat it as an RNG.
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.
18 /// It will fail if it there is insufficient data to fulfill a request.
23 /// use rand::{reader, Rng};
24 /// use std::io::MemReader;
26 /// let mut rng = reader::ReaderRng::new(MemReader::new(~[1,2,3,4,5,6,7,8]));
27 /// println!("{:x}", rng.gen::<uint>());
29 pub struct ReaderRng<R> {
33 impl<R: Reader> ReaderRng<R> {
34 /// Create a new `ReaderRng` from a `Reader`.
35 pub fn new(r: R) -> ReaderRng<R> {
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()
50 self.reader.read_be_u32().unwrap()
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()
58 self.reader.read_be_u64().unwrap()
61 fn fill_bytes(&mut self, v: &mut [u8]) {
62 if v.len() == 0 { return }
63 match self.reader.read(v) {
64 Ok(n) if n == v.len() => return,
65 Ok(n) => fail!("ReaderRng.fill_bytes could not fill buffer: \
66 read {} out of {} bytes.", n, v.len()),
67 Err(e) => fail!("ReaderRng.fill_bytes error: {}", e)
75 use std::io::MemReader;
80 fn test_reader_rng_u64() {
81 // transmute from the target to avoid endianness concerns.
82 let v = ~[1u64, 2u64, 3u64];
83 let bytes: ~[u8] = unsafe {cast::transmute(v)};
84 let mut rng = ReaderRng::new(MemReader::new(bytes));
86 assert_eq!(rng.next_u64(), 1);
87 assert_eq!(rng.next_u64(), 2);
88 assert_eq!(rng.next_u64(), 3);
91 fn test_reader_rng_u32() {
92 // transmute from the target to avoid endianness concerns.
93 let v = ~[1u32, 2u32, 3u32];
94 let bytes: ~[u8] = unsafe {cast::transmute(v)};
95 let mut rng = ReaderRng::new(MemReader::new(bytes));
97 assert_eq!(rng.next_u32(), 1);
98 assert_eq!(rng.next_u32(), 2);
99 assert_eq!(rng.next_u32(), 3);
102 fn test_reader_rng_fill_bytes() {
103 let v = [1u8, 2, 3, 4, 5, 6, 7, 8];
104 let mut w = [0u8, .. 8];
106 let mut rng = ReaderRng::new(MemReader::new(v.to_owned()));
114 fn test_reader_rng_insufficient_bytes() {
115 let mut rng = ReaderRng::new(MemReader::new(~[]));
116 let mut v = [0u8, .. 3];