|
111 | 111 | use std::time::Duration; |
112 | 112 | #[cfg(not(feature = "std"))] |
113 | 113 | use core::time::Duration; |
114 | | -use core::ops::{Range, RangeInclusive}; |
| 114 | +use core::ops::{Range, RangeInclusive, RangeTo, RangeToInclusive}; |
115 | 115 |
|
116 | 116 | use crate::Rng; |
117 | 117 | use crate::distributions::Distribution; |
@@ -306,6 +306,28 @@ impl<T: SampleUniform> Distribution<T> for RangeInclusive<T> { |
306 | 306 | } |
307 | 307 | } |
308 | 308 |
|
| 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 | + |
309 | 331 | /// Helper trait similar to [`Borrow`] but implemented |
310 | 332 | /// only for SampleUniform and references to SampleUniform in |
311 | 333 | /// order to resolve ambiguity issues. |
@@ -1294,10 +1316,14 @@ mod tests { |
1294 | 1316 | fn test_std_range_distribution() { |
1295 | 1317 | let mut rng = crate::test::rng(474); |
1296 | 1318 | 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); |
1301 | 1327 | } |
1302 | 1328 | } |
1303 | 1329 |
|
|
0 commit comments