From 5aaef138ff4d717ab723ac024c94c92539b4daa7 Mon Sep 17 00:00:00 2001 From: Huon Wilson Date: Thu, 10 Oct 2013 14:30:34 +1100 Subject: [PATCH] std::rand: Add RandSample for Sample-ing Rand types directly. --- src/libstd/rand/distributions.rs | 35 ++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/src/libstd/rand/distributions.rs b/src/libstd/rand/distributions.rs index 845d8bbc9525..0ee073a926bd 100644 --- a/src/libstd/rand/distributions.rs +++ b/src/libstd/rand/distributions.rs @@ -41,6 +41,20 @@ pub trait IndependentSample: Sample { fn ind_sample(&self, &mut R) -> Support; } +/// A wrapper for generating types that implement `Rand` via the +/// `Sample` & `IndependentSample` traits. +pub struct RandSample; + +impl Sample for RandSample { + fn sample(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) } +} + +impl IndependentSample for RandSample { + fn ind_sample(&self, rng: &mut R) -> Sup { + rng.gen() + } +} + mod ziggurat_tables; // inlining should mean there is no performance penalty for this @@ -166,3 +180,24 @@ impl Rand for Exp1 { pdf, zero_case)) } } + +#[cfg(test)] +mod tests { + use rand::*; + use super::*; + + struct ConstRand(uint); + impl Rand for ConstRand { + fn rand(_: &mut R) -> ConstRand { + ConstRand(0) + } + } + + #[test] + fn test_rand_sample() { + let mut rand_sample = RandSample::; + + assert_eq!(*rand_sample.sample(task_rng()), 0); + assert_eq!(*rand_sample.ind_sample(task_rng()), 0); + } +}