Skip to content

Commit

Permalink
Implement Distribution for Range(Inclusive)
Browse files Browse the repository at this point in the history
  • Loading branch information
Ralith committed Jun 10, 2019
1 parent 07f3676 commit bec87bd
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions src/distributions/uniform.rs
Expand Up @@ -291,6 +291,19 @@ impl<X: SampleUniform> From<::core::ops::RangeInclusive<X>> for Uniform<X> {
}
}

impl<T: SampleUniform> Distribution<T> for ::core::ops::Range<T> {
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
T::Sampler::sample_single(&self.start, &self.end, rng)
}
}

#[cfg(rustc_1_27)]
impl<T: SampleUniform> Distribution<T> for ::core::ops::RangeInclusive<T> {
fn sample<R: Rng + ?Sized>(&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.
Expand Down Expand Up @@ -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() {
Expand Down

0 comments on commit bec87bd

Please sign in to comment.