From bec87bd2de01fb4d13779a8fd0c3001c91621b1e Mon Sep 17 00:00:00 2001 From: Benjamin Saunders Date: Sun, 9 Jun 2019 19:04:39 -0700 Subject: [PATCH] Implement Distribution for Range(Inclusive) --- src/distributions/uniform.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/distributions/uniform.rs b/src/distributions/uniform.rs index a133b4e2ad..4b44e826cb 100644 --- a/src/distributions/uniform.rs +++ b/src/distributions/uniform.rs @@ -291,6 +291,19 @@ impl From<::core::ops::RangeInclusive> for Uniform { } } +impl Distribution for ::core::ops::Range { + fn sample(&self, rng: &mut R) -> T { + T::Sampler::sample_single(&self.start, &self.end, rng) + } +} + +#[cfg(rustc_1_27)] +impl Distribution for ::core::ops::RangeInclusive { + fn sample(&self, rng: &mut R) -> T { + T::Sampler::sample_single_inclusive(self.start(), self.end(), rng) + } +} + /// Helper trait similar to [`Borrow`] but implemented /// only for SampleUniform and references to SampleUniform in /// order to resolve ambiguity issues. @@ -1280,6 +1293,17 @@ mod tests { assert_eq!(r.inner.scale, 5.0); } + #[test] + fn test_std_range_distribution() { + let mut rng = ::test::rng(474); + for _ in 0..100 { + let x = rng.sample(0..10); + assert!(x >= 0 && x < 10); + let x = rng.sample(0..=10); + assert!(x >= 0 && x <= 10); + } + } + #[cfg(rustc_1_27)] #[test] fn test_uniform_from_std_range_inclusive() {