From 35bf020d65d24e36f7ddc0dfbaf5b137b7410a03 Mon Sep 17 00:00:00 2001 From: Vinzent Steinberg Date: Mon, 23 Jul 2018 13:45:26 +0200 Subject: [PATCH] Implement `From` for `Uniform` Fixes #556. --- Cargo.toml | 1 + src/distributions/uniform.rs | 19 +++++++++++++++++++ 2 files changed, 20 insertions(+) diff --git a/Cargo.toml b/Cargo.toml index c44a4d62f0a..65c61ad9182 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -25,6 +25,7 @@ alloc = ["rand_core/alloc"] # enables Vec and Box support (without std) i128_support = [] # enables i128 and u128 support simd_support = [] # enables SIMD support serde1 = ["serde", "serde_derive", "rand_core/serde1"] # enables serialization for PRNGs +rust_1_27 = [] # enables RangeInclusive support for Rust >= 1.27 [workspace] members = ["rand_core", "rand_isaac"] diff --git a/src/distributions/uniform.rs b/src/distributions/uniform.rs index bf68e45f51a..f6061932fbe 100644 --- a/src/distributions/uniform.rs +++ b/src/distributions/uniform.rs @@ -276,6 +276,13 @@ impl From<::core::ops::Range> for Uniform { } } +#[cfg(feature = "rust_1_27")] +impl From<::core::ops::RangeInclusive> for Uniform { + fn from(r: ::core::ops::RangeInclusive) -> Uniform { + Uniform::new_inclusive(r.start(), r.end()) + } +} + /// Helper trait similar to [`Borrow`] but implemented /// only for SampleUniform and references to SampleUniform in /// order to resolve ambiguity issues. @@ -1060,4 +1067,16 @@ mod tests { assert_eq!(r.inner.low, 2.0); assert_eq!(r.inner.scale, 5.0); } + + #[cfg(feature = "rust_1_27")] + #[test] + fn test_uniform_from_std_range_inclusive() { + let r = Uniform::from(2u32..=6); + assert_eq!(r.inner.low, 2); + assert_eq!(r.inner.range, 5); + let r = Uniform::from(2.0f64..=7.0); + assert_eq!(r.inner.low, 2.0); + assert!(r.inner.scale > 5.0); + assert!(r.inner.scale < 5.0 + 1e15); + } }