diff --git a/src/distributions/uniform.rs b/src/distributions/uniform.rs index 48d6f3f64f8..c3dd31f76d5 100644 --- a/src/distributions/uniform.rs +++ b/src/distributions/uniform.rs @@ -290,6 +290,18 @@ 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) + } +} + +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. @@ -1274,6 +1286,17 @@ mod tests { assert_eq!(r.inner.scale, 5.0); } + #[test] + fn test_std_range_distribution() { + let mut rng = crate::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); + } + } + #[test] fn test_uniform_from_std_range_inclusive() { let r = Uniform::from(2u32..=6); diff --git a/src/lib.rs b/src/lib.rs index 31f0169e1ae..b4de455ac4e 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -227,9 +227,10 @@ pub trait Rng: RngCore { /// use rand::distributions::Uniform; /// /// let mut rng = thread_rng(); - /// let x = rng.sample(Uniform::new(10u32, 15)); + /// let x = rng.sample(10u32..15); /// // Type annotation requires two types, the type and distribution; the - /// // distribution can be inferred. + /// // distribution can be inferred. `Uniform` is more efficient than the + /// // above range syntax if multiple samples are taken. /// let y = rng.sample::(Uniform::new(10, 15)); /// ``` fn sample>(&mut self, distr: D) -> T {