Skip to content

Commit bec87bd

Browse files
committed
Implement Distribution for Range(Inclusive)
1 parent 07f3676 commit bec87bd

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/distributions/uniform.rs

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -291,6 +291,19 @@ impl<X: SampleUniform> From<::core::ops::RangeInclusive<X>> for Uniform<X> {
291291
}
292292
}
293293

294+
impl<T: SampleUniform> Distribution<T> for ::core::ops::Range<T> {
295+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
296+
T::Sampler::sample_single(&self.start, &self.end, rng)
297+
}
298+
}
299+
300+
#[cfg(rustc_1_27)]
301+
impl<T: SampleUniform> Distribution<T> for ::core::ops::RangeInclusive<T> {
302+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> T {
303+
T::Sampler::sample_single_inclusive(self.start(), self.end(), rng)
304+
}
305+
}
306+
294307
/// Helper trait similar to [`Borrow`] but implemented
295308
/// only for SampleUniform and references to SampleUniform in
296309
/// order to resolve ambiguity issues.
@@ -1280,6 +1293,17 @@ mod tests {
12801293
assert_eq!(r.inner.scale, 5.0);
12811294
}
12821295

1296+
#[test]
1297+
fn test_std_range_distribution() {
1298+
let mut rng = ::test::rng(474);
1299+
for _ in 0..100 {
1300+
let x = rng.sample(0..10);
1301+
assert!(x >= 0 && x < 10);
1302+
let x = rng.sample(0..=10);
1303+
assert!(x >= 0 && x <= 10);
1304+
}
1305+
}
1306+
12831307
#[cfg(rustc_1_27)]
12841308
#[test]
12851309
fn test_uniform_from_std_range_inclusive() {

0 commit comments

Comments
 (0)