Skip to content

Commit 64af289

Browse files
committed
Implement Distribution for RangeTo(Inclusive) for unsigned ints
1 parent b25b657 commit 64af289

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

src/distributions/uniform.rs

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -111,7 +111,7 @@
111111
use std::time::Duration;
112112
#[cfg(not(feature = "std"))]
113113
use core::time::Duration;
114-
use core::ops::{Range, RangeInclusive};
114+
use core::ops::{Range, RangeInclusive, RangeTo, RangeToInclusive};
115115

116116
use crate::Rng;
117117
use crate::distributions::Distribution;
@@ -306,6 +306,28 @@ impl<T: SampleUniform> Distribution<T> for RangeInclusive<T> {
306306
}
307307
}
308308

309+
macro_rules! impl_distrib_range_to {
310+
($($ty:ty),*) => {
311+
$(
312+
impl Distribution<$ty> for RangeTo<$ty> {
313+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
314+
<$ty as SampleUniform>::Sampler::sample_single(0, self.end, rng)
315+
}
316+
}
317+
impl Distribution<$ty> for RangeToInclusive<$ty> {
318+
fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> $ty {
319+
<$ty as SampleUniform>::Sampler::sample_single_inclusive(0, self.end, rng)
320+
}
321+
}
322+
)*
323+
}
324+
}
325+
326+
impl_distrib_range_to!(usize, u8, u16, u32, u64);
327+
#[cfg(not(target_os = "emscripten"))]
328+
impl_distrib_range_to!(u128);
329+
330+
309331
/// Helper trait similar to [`Borrow`] but implemented
310332
/// only for SampleUniform and references to SampleUniform in
311333
/// order to resolve ambiguity issues.
@@ -1294,10 +1316,14 @@ mod tests {
12941316
fn test_std_range_distribution() {
12951317
let mut rng = crate::test::rng(474);
12961318
for _ in 0..100 {
1297-
let x = rng.sample(0..10);
1298-
assert!(x >= 0 && x < 10);
1299-
let x = rng.sample(0..=10);
1300-
assert!(x >= 0 && x <= 10);
1319+
let x = rng.sample(-5..5);
1320+
assert!(x >= -5 && x < 5);
1321+
let x = rng.sample(-5..=5);
1322+
assert!(x >= -5 && x <= 5);
1323+
let x = rng.sample(..10u8);
1324+
assert!(x < 10);
1325+
let x = rng.sample(..=10u8);
1326+
assert!(x <= 10);
13011327
}
13021328
}
13031329

0 commit comments

Comments
 (0)