Skip to content

Commit d1b3a18

Browse files
committed
Introduce sample and sample_iter into the Rng trait.
These traits take a reference to a `Distribution<T>` and generate values from that distribution.
1 parent be5beb1 commit d1b3a18

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

src/lib.rs

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,7 @@ use std::mem;
237237
use std::io;
238238
use std::rc::Rc;
239239
use std::num::wrapping::Wrapping as w;
240+
use std::num::Int;
240241

241242
pub use os::OsRng;
242243

@@ -416,6 +417,14 @@ pub trait Rng : Sized {
416417
Generator { rng: self, _marker: marker::PhantomData }
417418
}
418419

420+
fn sample<'a, T, D: Distribution<T>>(&'a mut self, distribution: &'a D) -> T {
421+
distribution.sample(self)
422+
}
423+
424+
fn sample_iter<'a, T, D: Distribution<T>>(&'a mut self, distribution: &'a D) -> SampleIter<'a, Self, D, T> {
425+
SampleIter { rng: self, distribution: distribution, _marker: marker::PhantomData }
426+
}
427+
419428
/// Generate a random value in the range [`low`, `high`).
420429
///
421430
/// This is a convenience wrapper around
@@ -535,6 +544,24 @@ impl<'a, T: Rand, R: Rng> Iterator for Generator<'a, T, R> {
535544
}
536545
}
537546

547+
pub struct SampleIter<'a, R:'a, D:'a, T> {
548+
rng: &'a mut R,
549+
distribution: &'a D,
550+
_marker: marker::PhantomData<fn() -> T>,
551+
}
552+
553+
impl <'a, R: Rng, D: Distribution<T>, T> Iterator for SampleIter<'a, R, D, T> {
554+
type Item = T;
555+
556+
fn next(&mut self) -> Option<T> {
557+
Some(self.distribution.sample(self.rng))
558+
}
559+
560+
fn size_hint(&self) -> (usize, Option<usize>) {
561+
(Int::max_value(), None)
562+
}
563+
}
564+
538565
/// Iterator which will continuously generate random ascii characters.
539566
///
540567
/// This iterator is created via the `gen_ascii_chars` method on `Rng`.

0 commit comments

Comments
 (0)