We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
In a simulation system, we repeatedly sample from immutable, non-empty ranges. I'd like to sample from a borrowed range like so:
let range = 0..10; let sampled = (&range).sample_single(&mut rng).unwrap(); // does not compile assert!(range.contains(&sampled));
Add support for sampling from borrowed Range and RangeInclusive.
Range
RangeInclusive
Proof of concept:
diff --git a/src/distr/uniform.rs b/src/distr/uniform.rs index b59fdbf7..b16ae123 100644 --- a/src/distr/uniform.rs +++ b/src/distr/uniform.rs @@ -439,6 +439,18 @@ impl<T: SampleUniform + PartialOrd> SampleRange<T> for Range<T> { } } +impl<T: SampleUniform + PartialOrd> SampleRange<T> for &Range<T> { + #[inline] + fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> Result<T, Error> { + T::Sampler::sample_single(&self.start, &self.end, rng) + } + + #[inline] + fn is_empty(&self) -> bool { + !(self.start < self.end) + } +} + impl<T: SampleUniform + PartialOrd> SampleRange<T> for RangeInclusive<T> { #[inline] fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> Result<T, Error> { @@ -451,6 +463,18 @@ impl<T: SampleUniform + PartialOrd> SampleRange<T> for RangeInclusive<T> { } } +impl<T: SampleUniform + PartialOrd> SampleRange<T> for &RangeInclusive<T> { + #[inline] + fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> Result<T, Error> { + T::Sampler::sample_single_inclusive(self.start(), self.end(), rng) + } + + #[inline] + fn is_empty(&self) -> bool { + !(self.start() <= self.end()) + } +} + macro_rules! impl_sample_range_u { ($t:ty) => { impl SampleRange<$t> for RangeTo<$t> { @@ -552,6 +576,19 @@ mod tests { } } + #[test] + fn can_sample_from_borrowed_range() { + let mut rng = crate::test::rng(804); + + let range = 0..10; + let sampled = (&range).sample_single(&mut rng).unwrap(); + assert!(range.contains(&sampled)); + + let range = 0..=10; + let sampled = (&range).sample_single(&mut rng).unwrap(); + assert!(range.contains(&sampled)); + } + #[test] fn value_stability() { fn test_samples<T: SampleUniform + Copy + fmt::Debug + PartialEq>(
I'm happy to write the MR if you like the idea.
The text was updated successfully, but these errors were encountered:
No branches or pull requests
Background
In a simulation system, we repeatedly sample from immutable, non-empty ranges. I'd like to sample from a borrowed range like so:
Feature request
Add support for sampling from borrowed
Range
andRangeInclusive
.Proof of concept:
I'm happy to write the MR if you like the idea.
The text was updated successfully, but these errors were encountered: