| 1 | use Source; |
| 2 | |
| 3 | /// A random value. |
| 4 | pub trait Value { |
| 5 | /// Read a random value. |
| 6 | fn read<S>(&mut S) -> Self where S: Source; |
| 7 | } |
| 8 | |
| 9 | macro_rules! implement( |
| 10 | ($reader:ident as $($kind:ty),*) => { |
| 11 | $(impl Value for $kind { |
| 12 | #[inline(always)] |
| 13 | fn read<S>(source: &mut S) -> Self where S: Source { |
| 14 | source.$reader() as $kind |
| 15 | } |
| 16 | })* |
| 17 | } |
| 18 | ); |
| 19 | |
| 20 | implement!(read_f64 as f32, f64); |
| 21 | implement!(read_u64 as i8, i16, i32, i64, isize); |
| 22 | implement!(read_u64 as u8, u16, u32, u64, usize); |
| 23 | |
| 24 | #[cfg(test)] |
| 25 | mod tests { |
| 26 | use {Source, Value, Xorshift128Plus}; |
| 27 | |
| 28 | #[test] |
| 29 | fn read() { |
| 30 | let mut source = Xorshift128Plus::new([42, 69]); |
| 31 | |
| 32 | macro_rules! read( |
| 33 | ($($kind:ident => [$one:expr, $two:expr],)*) => ({$( |
| 34 | assert_eq!(source.read::<$kind>(), $one); |
| 35 | assert_eq!($kind::read(&mut source), $two); |
| 36 | )*}); |
| 37 | ); |
| 38 | |
| 39 | read! { |
| 40 | i8 => [52, -34], |
| 41 | i16 => [-17348, -1036], |
| 42 | i32 => [948125133, -1432682055], |
| 43 | i64 => [-6330235019914458621, -4877218639256617945], |
| 44 | } |
| 45 | } |
| 46 | } |