Skip to content

Commit

Permalink
Introduce sample and sample_iter into the Rng trait.
Browse files Browse the repository at this point in the history
These traits take a reference to a `Distribution<T>` and generate values from that distribution.
  • Loading branch information
GrahamDennis committed Mar 21, 2015
1 parent be5beb1 commit d1b3a18
Showing 1 changed file with 27 additions and 0 deletions.
27 changes: 27 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,7 @@ use std::mem;
use std::io;
use std::rc::Rc;
use std::num::wrapping::Wrapping as w;
use std::num::Int;

pub use os::OsRng;

Expand Down Expand Up @@ -416,6 +417,14 @@ pub trait Rng : Sized {
Generator { rng: self, _marker: marker::PhantomData }
}

fn sample<'a, T, D: Distribution<T>>(&'a mut self, distribution: &'a D) -> T {
distribution.sample(self)
}

fn sample_iter<'a, T, D: Distribution<T>>(&'a mut self, distribution: &'a D) -> SampleIter<'a, Self, D, T> {
SampleIter { rng: self, distribution: distribution, _marker: marker::PhantomData }
}

/// Generate a random value in the range [`low`, `high`).
///
/// This is a convenience wrapper around
Expand Down Expand Up @@ -535,6 +544,24 @@ impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
}
}

pub struct SampleIter<'a, R:'a, D:'a, T> {
rng: &'a mut R,
distribution: &'a D,
_marker: marker::PhantomData<fn() -> T>,
}

impl <'a, R: Rng, D: Distribution<T>, T> Iterator for SampleIter<'a, R, D, T> {
type Item = T;

fn next(&mut self) -> Option<T> {
Some(self.distribution.sample(self.rng))
}

fn size_hint(&self) -> (usize, Option<usize>) {
(Int::max_value(), None)
}
}

/// Iterator which will continuously generate random ascii characters.
///
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.
Expand Down

0 comments on commit d1b3a18

Please sign in to comment.