Skip to content

Commit 5aaef13

Browse files
committed
std::rand: Add RandSample for Sample-ing Rand types directly.
1 parent 2cd772b commit 5aaef13

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

src/libstd/rand/distributions.rs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,20 @@ pub trait IndependentSample<Support>: Sample<Support> {
4141
fn ind_sample<R: Rng>(&self, &mut R) -> Support;
4242
}
4343

44+
/// A wrapper for generating types that implement `Rand` via the
45+
/// `Sample` & `IndependentSample` traits.
46+
pub struct RandSample<Sup>;
47+
48+
impl<Sup: Rand> Sample<Sup> for RandSample<Sup> {
49+
fn sample<R: Rng>(&mut self, rng: &mut R) -> Sup { self.ind_sample(rng) }
50+
}
51+
52+
impl<Sup: Rand> IndependentSample<Sup> for RandSample<Sup> {
53+
fn ind_sample<R: Rng>(&self, rng: &mut R) -> Sup {
54+
rng.gen()
55+
}
56+
}
57+
4458
mod ziggurat_tables;
4559

4660
// inlining should mean there is no performance penalty for this
@@ -166,3 +180,24 @@ impl Rand for Exp1 {
166180
pdf, zero_case))
167181
}
168182
}
183+
184+
#[cfg(test)]
185+
mod tests {
186+
use rand::*;
187+
use super::*;
188+
189+
struct ConstRand(uint);
190+
impl Rand for ConstRand {
191+
fn rand<R: Rng>(_: &mut R) -> ConstRand {
192+
ConstRand(0)
193+
}
194+
}
195+
196+
#[test]
197+
fn test_rand_sample() {
198+
let mut rand_sample = RandSample::<ConstRand>;
199+
200+
assert_eq!(*rand_sample.sample(task_rng()), 0);
201+
assert_eq!(*rand_sample.ind_sample(task_rng()), 0);
202+
}
203+
}

0 commit comments

Comments
 (0)