diff --git a/rand_distr/src/poisson.rs b/rand_distr/src/poisson.rs index 28f835ab7b8..436131f34c9 100644 --- a/rand_distr/src/poisson.rs +++ b/rand_distr/src/poisson.rs @@ -138,7 +138,7 @@ where Standard: Distribution } impl Distribution for Poisson -where Standard: Distribution + where Standard: Distribution { #[inline] fn sample(&self, rng: &mut R) -> u64 { @@ -147,10 +147,27 @@ where Standard: Distribution } } +impl Distribution for Poisson + where Standard: Distribution +{ + #[inline] + fn sample(&self, rng: &mut R) -> usize { + let result: N = self.sample(rng); + result.to_usize().unwrap() + } +} + #[cfg(test)] mod test { use super::*; + #[test] + fn poisson_usize() { + let poisson = Poisson::new(10.0).unwrap(); + let mut rng = crate::test::rng(123); + let s_usize: usize = poisson.sample(&mut rng); + } + #[test] fn test_poisson_10() { let poisson = Poisson::new(10.0).unwrap(); diff --git a/rand_distr/src/utils.rs b/rand_distr/src/utils.rs index 478aacf7625..bf79e06149a 100644 --- a/rand_distr/src/utils.rs +++ b/rand_distr/src/utils.rs @@ -42,6 +42,9 @@ pub trait Float: /// Support converting to an unsigned integer. fn to_u64(self) -> Option; + /// Support converting to an unsigned integer. + fn to_usize(self) -> Option; + /// Take the absolute value of self fn abs(self) -> Self; /// Take the largest integer less than or equal to self @@ -82,6 +85,15 @@ impl Float for f32 { } } + #[inline] + fn to_usize(self) -> Option { + if self >= 0. && self <= ::core::usize::MAX as f32 { + Some(self as usize) + } else { + None + } + } + #[inline] fn abs(self) -> Self { self.abs() @@ -145,6 +157,14 @@ impl Float for f64 { None } } + #[inline] + fn to_usize(self) -> Option { + if self >= 0. && self <= ::core::usize::MAX as f64 { + Some(self as usize) + } else { + None + } + } #[inline] fn abs(self) -> Self {