• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2018-2020 Developers of the Rand project.
2 // Copyright 2017 The Rust Project Developers.
3 //
4 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5 // https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6 // <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
7 // option. This file may not be copied, modified, or distributed
8 // except according to those terms.
9 
10 //! A distribution uniformly sampling numbers within a given range.
11 //!
12 //! [`Uniform`] is the standard distribution to sample uniformly from a range;
13 //! e.g. `Uniform::new_inclusive(1, 6)` can sample integers from 1 to 6, like a
14 //! standard die. [`Rng::gen_range`] supports any type supported by
15 //! [`Uniform`].
16 //!
17 //! This distribution is provided with support for several primitive types
18 //! (all integer and floating-point types) as well as [`std::time::Duration`],
19 //! and supports extension to user-defined types via a type-specific *back-end*
20 //! implementation.
21 //!
22 //! The types [`UniformInt`], [`UniformFloat`] and [`UniformDuration`] are the
23 //! back-ends supporting sampling from primitive integer and floating-point
24 //! ranges as well as from [`std::time::Duration`]; these types do not normally
25 //! need to be used directly (unless implementing a derived back-end).
26 //!
27 //! # Example usage
28 //!
29 //! ```
30 //! use rand::{Rng, thread_rng};
31 //! use rand::distributions::Uniform;
32 //!
33 //! let mut rng = thread_rng();
34 //! let side = Uniform::new(-10.0, 10.0);
35 //!
36 //! // sample between 1 and 10 points
37 //! for _ in 0..rng.gen_range(1..=10) {
38 //!     // sample a point from the square with sides -10 - 10 in two dimensions
39 //!     let (x, y) = (rng.sample(side), rng.sample(side));
40 //!     println!("Point: {}, {}", x, y);
41 //! }
42 //! ```
43 //!
44 //! # Extending `Uniform` to support a custom type
45 //!
46 //! To extend [`Uniform`] to support your own types, write a back-end which
47 //! implements the [`UniformSampler`] trait, then implement the [`SampleUniform`]
48 //! helper trait to "register" your back-end. See the `MyF32` example below.
49 //!
50 //! At a minimum, the back-end needs to store any parameters needed for sampling
51 //! (e.g. the target range) and implement `new`, `new_inclusive` and `sample`.
52 //! Those methods should include an assert to check the range is valid (i.e.
53 //! `low < high`). The example below merely wraps another back-end.
54 //!
55 //! The `new`, `new_inclusive` and `sample_single` functions use arguments of
56 //! type SampleBorrow<X> in order to support passing in values by reference or
57 //! by value. In the implementation of these functions, you can choose to
58 //! simply use the reference returned by [`SampleBorrow::borrow`], or you can choose
59 //! to copy or clone the value, whatever is appropriate for your type.
60 //!
61 //! ```
62 //! use rand::prelude::*;
63 //! use rand::distributions::uniform::{Uniform, SampleUniform,
64 //!         UniformSampler, UniformFloat, SampleBorrow};
65 //!
66 //! struct MyF32(f32);
67 //!
68 //! #[derive(Clone, Copy, Debug)]
69 //! struct UniformMyF32(UniformFloat<f32>);
70 //!
71 //! impl UniformSampler for UniformMyF32 {
72 //!     type X = MyF32;
73 //!     fn new<B1, B2>(low: B1, high: B2) -> Self
74 //!         where B1: SampleBorrow<Self::X> + Sized,
75 //!               B2: SampleBorrow<Self::X> + Sized
76 //!     {
77 //!         UniformMyF32(UniformFloat::<f32>::new(low.borrow().0, high.borrow().0))
78 //!     }
79 //!     fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
80 //!         where B1: SampleBorrow<Self::X> + Sized,
81 //!               B2: SampleBorrow<Self::X> + Sized
82 //!     {
83 //!         UniformSampler::new(low, high)
84 //!     }
85 //!     fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
86 //!         MyF32(self.0.sample(rng))
87 //!     }
88 //! }
89 //!
90 //! impl SampleUniform for MyF32 {
91 //!     type Sampler = UniformMyF32;
92 //! }
93 //!
94 //! let (low, high) = (MyF32(17.0f32), MyF32(22.0f32));
95 //! let uniform = Uniform::new(low, high);
96 //! let x = uniform.sample(&mut thread_rng());
97 //! ```
98 //!
99 //! [`SampleUniform`]: crate::distributions::uniform::SampleUniform
100 //! [`UniformSampler`]: crate::distributions::uniform::UniformSampler
101 //! [`UniformInt`]: crate::distributions::uniform::UniformInt
102 //! [`UniformFloat`]: crate::distributions::uniform::UniformFloat
103 //! [`UniformDuration`]: crate::distributions::uniform::UniformDuration
104 //! [`SampleBorrow::borrow`]: crate::distributions::uniform::SampleBorrow::borrow
105 
106 #[cfg(not(feature = "std"))] use core::time::Duration;
107 #[cfg(feature = "std")] use std::time::Duration;
108 use core::ops::{Range, RangeInclusive};
109 
110 use crate::distributions::float::IntoFloat;
111 use crate::distributions::utils::{BoolAsSIMD, FloatAsSIMD, FloatSIMDUtils, WideningMultiply};
112 use crate::distributions::Distribution;
113 use crate::{Rng, RngCore};
114 
115 #[cfg(not(feature = "std"))]
116 #[allow(unused_imports)] // rustc doesn't detect that this is actually used
117 use crate::distributions::utils::Float;
118 
119 #[cfg(feature = "simd_support")] use packed_simd::*;
120 
121 #[cfg(feature = "serde1")]
122 use serde::{Serialize, Deserialize};
123 
124 /// Sample values uniformly between two bounds.
125 ///
126 /// [`Uniform::new`] and [`Uniform::new_inclusive`] construct a uniform
127 /// distribution sampling from the given range; these functions may do extra
128 /// work up front to make sampling of multiple values faster. If only one sample
129 /// from the range is required, [`Rng::gen_range`] can be more efficient.
130 ///
131 /// When sampling from a constant range, many calculations can happen at
132 /// compile-time and all methods should be fast; for floating-point ranges and
133 /// the full range of integer types this should have comparable performance to
134 /// the `Standard` distribution.
135 ///
136 /// Steps are taken to avoid bias which might be present in naive
137 /// implementations; for example `rng.gen::<u8>() % 170` samples from the range
138 /// `[0, 169]` but is twice as likely to select numbers less than 85 than other
139 /// values. Further, the implementations here give more weight to the high-bits
140 /// generated by the RNG than the low bits, since with some RNGs the low-bits
141 /// are of lower quality than the high bits.
142 ///
143 /// Implementations must sample in `[low, high)` range for
144 /// `Uniform::new(low, high)`, i.e., excluding `high`. In particular, care must
145 /// be taken to ensure that rounding never results values `< low` or `>= high`.
146 ///
147 /// # Example
148 ///
149 /// ```
150 /// use rand::distributions::{Distribution, Uniform};
151 ///
152 /// let between = Uniform::from(10..10000);
153 /// let mut rng = rand::thread_rng();
154 /// let mut sum = 0;
155 /// for _ in 0..1000 {
156 ///     sum += between.sample(&mut rng);
157 /// }
158 /// println!("{}", sum);
159 /// ```
160 ///
161 /// For a single sample, [`Rng::gen_range`] may be prefered:
162 ///
163 /// ```
164 /// use rand::Rng;
165 ///
166 /// let mut rng = rand::thread_rng();
167 /// println!("{}", rng.gen_range(0..10));
168 /// ```
169 ///
170 /// [`new`]: Uniform::new
171 /// [`new_inclusive`]: Uniform::new_inclusive
172 /// [`Rng::gen_range`]: Rng::gen_range
173 #[derive(Clone, Copy, Debug)]
174 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
175 pub struct Uniform<X: SampleUniform>(X::Sampler);
176 
177 impl<X: SampleUniform> Uniform<X> {
178     /// Create a new `Uniform` instance which samples uniformly from the half
179     /// open range `[low, high)` (excluding `high`). Panics if `low >= high`.
new<B1, B2>(low: B1, high: B2) -> Uniform<X> where B1: SampleBorrow<X> + Sized, B2: SampleBorrow<X> + Sized,180     pub fn new<B1, B2>(low: B1, high: B2) -> Uniform<X>
181     where
182         B1: SampleBorrow<X> + Sized,
183         B2: SampleBorrow<X> + Sized,
184     {
185         Uniform(X::Sampler::new(low, high))
186     }
187 
188     /// Create a new `Uniform` instance which samples uniformly from the closed
189     /// range `[low, high]` (inclusive). Panics if `low > high`.
new_inclusive<B1, B2>(low: B1, high: B2) -> Uniform<X> where B1: SampleBorrow<X> + Sized, B2: SampleBorrow<X> + Sized,190     pub fn new_inclusive<B1, B2>(low: B1, high: B2) -> Uniform<X>
191     where
192         B1: SampleBorrow<X> + Sized,
193         B2: SampleBorrow<X> + Sized,
194     {
195         Uniform(X::Sampler::new_inclusive(low, high))
196     }
197 }
198 
199 impl<X: SampleUniform> Distribution<X> for Uniform<X> {
sample<R: Rng + ?Sized>(&self, rng: &mut R) -> X200     fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> X {
201         self.0.sample(rng)
202     }
203 }
204 
205 /// Helper trait for creating objects using the correct implementation of
206 /// [`UniformSampler`] for the sampling type.
207 ///
208 /// See the [module documentation] on how to implement [`Uniform`] range
209 /// sampling for a custom type.
210 ///
211 /// [module documentation]: crate::distributions::uniform
212 pub trait SampleUniform: Sized {
213     /// The `UniformSampler` implementation supporting type `X`.
214     type Sampler: UniformSampler<X = Self>;
215 }
216 
217 /// Helper trait handling actual uniform sampling.
218 ///
219 /// See the [module documentation] on how to implement [`Uniform`] range
220 /// sampling for a custom type.
221 ///
222 /// Implementation of [`sample_single`] is optional, and is only useful when
223 /// the implementation can be faster than `Self::new(low, high).sample(rng)`.
224 ///
225 /// [module documentation]: crate::distributions::uniform
226 /// [`sample_single`]: UniformSampler::sample_single
227 pub trait UniformSampler: Sized {
228     /// The type sampled by this implementation.
229     type X;
230 
231     /// Construct self, with inclusive lower bound and exclusive upper bound
232     /// `[low, high)`.
233     ///
234     /// Usually users should not call this directly but instead use
235     /// `Uniform::new`, which asserts that `low < high` before calling this.
new<B1, B2>(low: B1, high: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized236     fn new<B1, B2>(low: B1, high: B2) -> Self
237     where
238         B1: SampleBorrow<Self::X> + Sized,
239         B2: SampleBorrow<Self::X> + Sized;
240 
241     /// Construct self, with inclusive bounds `[low, high]`.
242     ///
243     /// Usually users should not call this directly but instead use
244     /// `Uniform::new_inclusive`, which asserts that `low <= high` before
245     /// calling this.
new_inclusive<B1, B2>(low: B1, high: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized246     fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
247     where
248         B1: SampleBorrow<Self::X> + Sized,
249         B2: SampleBorrow<Self::X> + Sized;
250 
251     /// Sample a value.
sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X252     fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X;
253 
254     /// Sample a single value uniformly from a range with inclusive lower bound
255     /// and exclusive upper bound `[low, high)`.
256     ///
257     /// By default this is implemented using
258     /// `UniformSampler::new(low, high).sample(rng)`. However, for some types
259     /// more optimal implementations for single usage may be provided via this
260     /// method (which is the case for integers and floats).
261     /// Results may not be identical.
262     ///
263     /// Note that to use this method in a generic context, the type needs to be
264     /// retrieved via `SampleUniform::Sampler` as follows:
265     /// ```
266     /// use rand::{thread_rng, distributions::uniform::{SampleUniform, UniformSampler}};
267     /// # #[allow(unused)]
268     /// fn sample_from_range<T: SampleUniform>(lb: T, ub: T) -> T {
269     ///     let mut rng = thread_rng();
270     ///     <T as SampleUniform>::Sampler::sample_single(lb, ub, &mut rng)
271     /// }
272     /// ```
sample_single<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) -> Self::X where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized,273     fn sample_single<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) -> Self::X
274     where
275         B1: SampleBorrow<Self::X> + Sized,
276         B2: SampleBorrow<Self::X> + Sized,
277     {
278         let uniform: Self = UniformSampler::new(low, high);
279         uniform.sample(rng)
280     }
281 
282     /// Sample a single value uniformly from a range with inclusive lower bound
283     /// and inclusive upper bound `[low, high]`.
284     ///
285     /// By default this is implemented using
286     /// `UniformSampler::new_inclusive(low, high).sample(rng)`. However, for
287     /// some types more optimal implementations for single usage may be provided
288     /// via this method.
289     /// Results may not be identical.
sample_single_inclusive<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R) -> Self::X where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized290     fn sample_single_inclusive<R: Rng + ?Sized, B1, B2>(low: B1, high: B2, rng: &mut R)
291         -> Self::X
292         where B1: SampleBorrow<Self::X> + Sized,
293               B2: SampleBorrow<Self::X> + Sized
294     {
295         let uniform: Self = UniformSampler::new_inclusive(low, high);
296         uniform.sample(rng)
297     }
298 }
299 
300 impl<X: SampleUniform> From<Range<X>> for Uniform<X> {
from(r: ::core::ops::Range<X>) -> Uniform<X>301     fn from(r: ::core::ops::Range<X>) -> Uniform<X> {
302         Uniform::new(r.start, r.end)
303     }
304 }
305 
306 impl<X: SampleUniform> From<RangeInclusive<X>> for Uniform<X> {
from(r: ::core::ops::RangeInclusive<X>) -> Uniform<X>307     fn from(r: ::core::ops::RangeInclusive<X>) -> Uniform<X> {
308         Uniform::new_inclusive(r.start(), r.end())
309     }
310 }
311 
312 
313 /// Helper trait similar to [`Borrow`] but implemented
314 /// only for SampleUniform and references to SampleUniform in
315 /// order to resolve ambiguity issues.
316 ///
317 /// [`Borrow`]: std::borrow::Borrow
318 pub trait SampleBorrow<Borrowed> {
319     /// Immutably borrows from an owned value. See [`Borrow::borrow`]
320     ///
321     /// [`Borrow::borrow`]: std::borrow::Borrow::borrow
borrow(&self) -> &Borrowed322     fn borrow(&self) -> &Borrowed;
323 }
324 impl<Borrowed> SampleBorrow<Borrowed> for Borrowed
325 where Borrowed: SampleUniform
326 {
327     #[inline(always)]
borrow(&self) -> &Borrowed328     fn borrow(&self) -> &Borrowed {
329         self
330     }
331 }
332 impl<'a, Borrowed> SampleBorrow<Borrowed> for &'a Borrowed
333 where Borrowed: SampleUniform
334 {
335     #[inline(always)]
borrow(&self) -> &Borrowed336     fn borrow(&self) -> &Borrowed {
337         *self
338     }
339 }
340 
341 /// Range that supports generating a single sample efficiently.
342 ///
343 /// Any type implementing this trait can be used to specify the sampled range
344 /// for `Rng::gen_range`.
345 pub trait SampleRange<T> {
346     /// Generate a sample from the given range.
sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T347     fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T;
348 
349     /// Check whether the range is empty.
is_empty(&self) -> bool350     fn is_empty(&self) -> bool;
351 }
352 
353 impl<T: SampleUniform + PartialOrd> SampleRange<T> for Range<T> {
354     #[inline]
sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T355     fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T {
356         T::Sampler::sample_single(self.start, self.end, rng)
357     }
358 
359     #[inline]
is_empty(&self) -> bool360     fn is_empty(&self) -> bool {
361         !(self.start < self.end)
362     }
363 }
364 
365 impl<T: SampleUniform + PartialOrd> SampleRange<T> for RangeInclusive<T> {
366     #[inline]
sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T367     fn sample_single<R: RngCore + ?Sized>(self, rng: &mut R) -> T {
368         T::Sampler::sample_single_inclusive(self.start(), self.end(), rng)
369     }
370 
371     #[inline]
is_empty(&self) -> bool372     fn is_empty(&self) -> bool {
373         !(self.start() <= self.end())
374     }
375 }
376 
377 
378 ////////////////////////////////////////////////////////////////////////////////
379 
380 // What follows are all back-ends.
381 
382 
383 /// The back-end implementing [`UniformSampler`] for integer types.
384 ///
385 /// Unless you are implementing [`UniformSampler`] for your own type, this type
386 /// should not be used directly, use [`Uniform`] instead.
387 ///
388 /// # Implementation notes
389 ///
390 /// For simplicity, we use the same generic struct `UniformInt<X>` for all
391 /// integer types `X`. This gives us only one field type, `X`; to store unsigned
392 /// values of this size, we take use the fact that these conversions are no-ops.
393 ///
394 /// For a closed range, the number of possible numbers we should generate is
395 /// `range = (high - low + 1)`. To avoid bias, we must ensure that the size of
396 /// our sample space, `zone`, is a multiple of `range`; other values must be
397 /// rejected (by replacing with a new random sample).
398 ///
399 /// As a special case, we use `range = 0` to represent the full range of the
400 /// result type (i.e. for `new_inclusive($ty::MIN, $ty::MAX)`).
401 ///
402 /// The optimum `zone` is the largest product of `range` which fits in our
403 /// (unsigned) target type. We calculate this by calculating how many numbers we
404 /// must reject: `reject = (MAX + 1) % range = (MAX - range + 1) % range`. Any (large)
405 /// product of `range` will suffice, thus in `sample_single` we multiply by a
406 /// power of 2 via bit-shifting (faster but may cause more rejections).
407 ///
408 /// The smallest integer PRNGs generate is `u32`. For 8- and 16-bit outputs we
409 /// use `u32` for our `zone` and samples (because it's not slower and because
410 /// it reduces the chance of having to reject a sample). In this case we cannot
411 /// store `zone` in the target type since it is too large, however we know
412 /// `ints_to_reject < range <= $unsigned::MAX`.
413 ///
414 /// An alternative to using a modulus is widening multiply: After a widening
415 /// multiply by `range`, the result is in the high word. Then comparing the low
416 /// word against `zone` makes sure our distribution is uniform.
417 #[derive(Clone, Copy, Debug)]
418 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
419 pub struct UniformInt<X> {
420     low: X,
421     range: X,
422     z: X, // either ints_to_reject or zone depending on implementation
423 }
424 
425 macro_rules! uniform_int_impl {
426     ($ty:ty, $unsigned:ident, $u_large:ident) => {
427         impl SampleUniform for $ty {
428             type Sampler = UniformInt<$ty>;
429         }
430 
431         impl UniformSampler for UniformInt<$ty> {
432             // We play free and fast with unsigned vs signed here
433             // (when $ty is signed), but that's fine, since the
434             // contract of this macro is for $ty and $unsigned to be
435             // "bit-equal", so casting between them is a no-op.
436 
437             type X = $ty;
438 
439             #[inline] // if the range is constant, this helps LLVM to do the
440                       // calculations at compile-time.
441             fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
442             where
443                 B1: SampleBorrow<Self::X> + Sized,
444                 B2: SampleBorrow<Self::X> + Sized,
445             {
446                 let low = *low_b.borrow();
447                 let high = *high_b.borrow();
448                 assert!(low < high, "Uniform::new called with `low >= high`");
449                 UniformSampler::new_inclusive(low, high - 1)
450             }
451 
452             #[inline] // if the range is constant, this helps LLVM to do the
453                       // calculations at compile-time.
454             fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
455             where
456                 B1: SampleBorrow<Self::X> + Sized,
457                 B2: SampleBorrow<Self::X> + Sized,
458             {
459                 let low = *low_b.borrow();
460                 let high = *high_b.borrow();
461                 assert!(
462                     low <= high,
463                     "Uniform::new_inclusive called with `low > high`"
464                 );
465                 let unsigned_max = ::core::$u_large::MAX;
466 
467                 let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned;
468                 let ints_to_reject = if range > 0 {
469                     let range = $u_large::from(range);
470                     (unsigned_max - range + 1) % range
471                 } else {
472                     0
473                 };
474 
475                 UniformInt {
476                     low,
477                     // These are really $unsigned values, but store as $ty:
478                     range: range as $ty,
479                     z: ints_to_reject as $unsigned as $ty,
480                 }
481             }
482 
483             #[inline]
484             fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
485                 let range = self.range as $unsigned as $u_large;
486                 if range > 0 {
487                     let unsigned_max = ::core::$u_large::MAX;
488                     let zone = unsigned_max - (self.z as $unsigned as $u_large);
489                     loop {
490                         let v: $u_large = rng.gen();
491                         let (hi, lo) = v.wmul(range);
492                         if lo <= zone {
493                             return self.low.wrapping_add(hi as $ty);
494                         }
495                     }
496                 } else {
497                     // Sample from the entire integer range.
498                     rng.gen()
499                 }
500             }
501 
502             #[inline]
503             fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
504             where
505                 B1: SampleBorrow<Self::X> + Sized,
506                 B2: SampleBorrow<Self::X> + Sized,
507             {
508                 let low = *low_b.borrow();
509                 let high = *high_b.borrow();
510                 assert!(low < high, "UniformSampler::sample_single: low >= high");
511                 Self::sample_single_inclusive(low, high - 1, rng)
512             }
513 
514             #[inline]
515             fn sample_single_inclusive<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
516             where
517                 B1: SampleBorrow<Self::X> + Sized,
518                 B2: SampleBorrow<Self::X> + Sized,
519             {
520                 let low = *low_b.borrow();
521                 let high = *high_b.borrow();
522                 assert!(low <= high, "UniformSampler::sample_single_inclusive: low > high");
523                 let range = high.wrapping_sub(low).wrapping_add(1) as $unsigned as $u_large;
524                 // If the above resulted in wrap-around to 0, the range is $ty::MIN..=$ty::MAX,
525                 // and any integer will do.
526                 if range == 0 {
527                     return rng.gen();
528                 }
529 
530                 let zone = if ::core::$unsigned::MAX <= ::core::u16::MAX as $unsigned {
531                     // Using a modulus is faster than the approximation for
532                     // i8 and i16. I suppose we trade the cost of one
533                     // modulus for near-perfect branch prediction.
534                     let unsigned_max: $u_large = ::core::$u_large::MAX;
535                     let ints_to_reject = (unsigned_max - range + 1) % range;
536                     unsigned_max - ints_to_reject
537                 } else {
538                     // conservative but fast approximation. `- 1` is necessary to allow the
539                     // same comparison without bias.
540                     (range << range.leading_zeros()).wrapping_sub(1)
541                 };
542 
543                 loop {
544                     let v: $u_large = rng.gen();
545                     let (hi, lo) = v.wmul(range);
546                     if lo <= zone {
547                         return low.wrapping_add(hi as $ty);
548                     }
549                 }
550             }
551         }
552     };
553 }
554 
555 uniform_int_impl! { i8, u8, u32 }
556 uniform_int_impl! { i16, u16, u32 }
557 uniform_int_impl! { i32, u32, u32 }
558 uniform_int_impl! { i64, u64, u64 }
559 #[cfg(not(target_os = "emscripten"))]
560 uniform_int_impl! { i128, u128, u128 }
561 uniform_int_impl! { isize, usize, usize }
562 uniform_int_impl! { u8, u8, u32 }
563 uniform_int_impl! { u16, u16, u32 }
564 uniform_int_impl! { u32, u32, u32 }
565 uniform_int_impl! { u64, u64, u64 }
566 uniform_int_impl! { usize, usize, usize }
567 #[cfg(not(target_os = "emscripten"))]
568 uniform_int_impl! { u128, u128, u128 }
569 
570 #[cfg(feature = "simd_support")]
571 macro_rules! uniform_simd_int_impl {
572     ($ty:ident, $unsigned:ident, $u_scalar:ident) => {
573         // The "pick the largest zone that can fit in an `u32`" optimization
574         // is less useful here. Multiple lanes complicate things, we don't
575         // know the PRNG's minimal output size, and casting to a larger vector
576         // is generally a bad idea for SIMD performance. The user can still
577         // implement it manually.
578 
579         // TODO: look into `Uniform::<u32x4>::new(0u32, 100)` functionality
580         //       perhaps `impl SampleUniform for $u_scalar`?
581         impl SampleUniform for $ty {
582             type Sampler = UniformInt<$ty>;
583         }
584 
585         impl UniformSampler for UniformInt<$ty> {
586             type X = $ty;
587 
588             #[inline] // if the range is constant, this helps LLVM to do the
589                       // calculations at compile-time.
590             fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
591                 where B1: SampleBorrow<Self::X> + Sized,
592                       B2: SampleBorrow<Self::X> + Sized
593             {
594                 let low = *low_b.borrow();
595                 let high = *high_b.borrow();
596                 assert!(low.lt(high).all(), "Uniform::new called with `low >= high`");
597                 UniformSampler::new_inclusive(low, high - 1)
598             }
599 
600             #[inline] // if the range is constant, this helps LLVM to do the
601                       // calculations at compile-time.
602             fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
603                 where B1: SampleBorrow<Self::X> + Sized,
604                       B2: SampleBorrow<Self::X> + Sized
605             {
606                 let low = *low_b.borrow();
607                 let high = *high_b.borrow();
608                 assert!(low.le(high).all(),
609                         "Uniform::new_inclusive called with `low > high`");
610                 let unsigned_max = ::core::$u_scalar::MAX;
611 
612                 // NOTE: these may need to be replaced with explicitly
613                 // wrapping operations if `packed_simd` changes
614                 let range: $unsigned = ((high - low) + 1).cast();
615                 // `% 0` will panic at runtime.
616                 let not_full_range = range.gt($unsigned::splat(0));
617                 // replacing 0 with `unsigned_max` allows a faster `select`
618                 // with bitwise OR
619                 let modulo = not_full_range.select(range, $unsigned::splat(unsigned_max));
620                 // wrapping addition
621                 let ints_to_reject = (unsigned_max - range + 1) % modulo;
622                 // When `range` is 0, `lo` of `v.wmul(range)` will always be
623                 // zero which means only one sample is needed.
624                 let zone = unsigned_max - ints_to_reject;
625 
626                 UniformInt {
627                     low,
628                     // These are really $unsigned values, but store as $ty:
629                     range: range.cast(),
630                     z: zone.cast(),
631                 }
632             }
633 
634             fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
635                 let range: $unsigned = self.range.cast();
636                 let zone: $unsigned = self.z.cast();
637 
638                 // This might seem very slow, generating a whole new
639                 // SIMD vector for every sample rejection. For most uses
640                 // though, the chance of rejection is small and provides good
641                 // general performance. With multiple lanes, that chance is
642                 // multiplied. To mitigate this, we replace only the lanes of
643                 // the vector which fail, iteratively reducing the chance of
644                 // rejection. The replacement method does however add a little
645                 // overhead. Benchmarking or calculating probabilities might
646                 // reveal contexts where this replacement method is slower.
647                 let mut v: $unsigned = rng.gen();
648                 loop {
649                     let (hi, lo) = v.wmul(range);
650                     let mask = lo.le(zone);
651                     if mask.all() {
652                         let hi: $ty = hi.cast();
653                         // wrapping addition
654                         let result = self.low + hi;
655                         // `select` here compiles to a blend operation
656                         // When `range.eq(0).none()` the compare and blend
657                         // operations are avoided.
658                         let v: $ty = v.cast();
659                         return range.gt($unsigned::splat(0)).select(result, v);
660                     }
661                     // Replace only the failing lanes
662                     v = mask.select(v, rng.gen());
663                 }
664             }
665         }
666     };
667 
668     // bulk implementation
669     ($(($unsigned:ident, $signed:ident),)+ $u_scalar:ident) => {
670         $(
671             uniform_simd_int_impl!($unsigned, $unsigned, $u_scalar);
672             uniform_simd_int_impl!($signed, $unsigned, $u_scalar);
673         )+
674     };
675 }
676 
677 #[cfg(feature = "simd_support")]
678 uniform_simd_int_impl! {
679     (u64x2, i64x2),
680     (u64x4, i64x4),
681     (u64x8, i64x8),
682     u64
683 }
684 
685 #[cfg(feature = "simd_support")]
686 uniform_simd_int_impl! {
687     (u32x2, i32x2),
688     (u32x4, i32x4),
689     (u32x8, i32x8),
690     (u32x16, i32x16),
691     u32
692 }
693 
694 #[cfg(feature = "simd_support")]
695 uniform_simd_int_impl! {
696     (u16x2, i16x2),
697     (u16x4, i16x4),
698     (u16x8, i16x8),
699     (u16x16, i16x16),
700     (u16x32, i16x32),
701     u16
702 }
703 
704 #[cfg(feature = "simd_support")]
705 uniform_simd_int_impl! {
706     (u8x2, i8x2),
707     (u8x4, i8x4),
708     (u8x8, i8x8),
709     (u8x16, i8x16),
710     (u8x32, i8x32),
711     (u8x64, i8x64),
712     u8
713 }
714 
715 impl SampleUniform for char {
716     type Sampler = UniformChar;
717 }
718 
719 /// The back-end implementing [`UniformSampler`] for `char`.
720 ///
721 /// Unless you are implementing [`UniformSampler`] for your own type, this type
722 /// should not be used directly, use [`Uniform`] instead.
723 ///
724 /// This differs from integer range sampling since the range `0xD800..=0xDFFF`
725 /// are used for surrogate pairs in UCS and UTF-16, and consequently are not
726 /// valid Unicode code points. We must therefore avoid sampling values in this
727 /// range.
728 #[derive(Clone, Copy, Debug)]
729 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
730 pub struct UniformChar {
731     sampler: UniformInt<u32>,
732 }
733 
734 /// UTF-16 surrogate range start
735 const CHAR_SURROGATE_START: u32 = 0xD800;
736 /// UTF-16 surrogate range size
737 const CHAR_SURROGATE_LEN: u32 = 0xE000 - CHAR_SURROGATE_START;
738 
739 /// Convert `char` to compressed `u32`
char_to_comp_u32(c: char) -> u32740 fn char_to_comp_u32(c: char) -> u32 {
741     match c as u32 {
742         c if c >= CHAR_SURROGATE_START => c - CHAR_SURROGATE_LEN,
743         c => c,
744     }
745 }
746 
747 impl UniformSampler for UniformChar {
748     type X = char;
749 
750     #[inline] // if the range is constant, this helps LLVM to do the
751               // calculations at compile-time.
new<B1, B2>(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized,752     fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
753     where
754         B1: SampleBorrow<Self::X> + Sized,
755         B2: SampleBorrow<Self::X> + Sized,
756     {
757         let low = char_to_comp_u32(*low_b.borrow());
758         let high = char_to_comp_u32(*high_b.borrow());
759         let sampler = UniformInt::<u32>::new(low, high);
760         UniformChar { sampler }
761     }
762 
763     #[inline] // if the range is constant, this helps LLVM to do the
764               // calculations at compile-time.
new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized,765     fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
766     where
767         B1: SampleBorrow<Self::X> + Sized,
768         B2: SampleBorrow<Self::X> + Sized,
769     {
770         let low = char_to_comp_u32(*low_b.borrow());
771         let high = char_to_comp_u32(*high_b.borrow());
772         let sampler = UniformInt::<u32>::new_inclusive(low, high);
773         UniformChar { sampler }
774     }
775 
sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X776     fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
777         let mut x = self.sampler.sample(rng);
778         if x >= CHAR_SURROGATE_START {
779             x += CHAR_SURROGATE_LEN;
780         }
781         // SAFETY: x must not be in surrogate range or greater than char::MAX.
782         // This relies on range constructors which accept char arguments.
783         // Validity of input char values is assumed.
784         unsafe { core::char::from_u32_unchecked(x) }
785     }
786 }
787 
788 /// The back-end implementing [`UniformSampler`] for floating-point types.
789 ///
790 /// Unless you are implementing [`UniformSampler`] for your own type, this type
791 /// should not be used directly, use [`Uniform`] instead.
792 ///
793 /// # Implementation notes
794 ///
795 /// Instead of generating a float in the `[0, 1)` range using [`Standard`], the
796 /// `UniformFloat` implementation converts the output of an PRNG itself. This
797 /// way one or two steps can be optimized out.
798 ///
799 /// The floats are first converted to a value in the `[1, 2)` interval using a
800 /// transmute-based method, and then mapped to the expected range with a
801 /// multiply and addition. Values produced this way have what equals 23 bits of
802 /// random digits for an `f32`, and 52 for an `f64`.
803 ///
804 /// [`new`]: UniformSampler::new
805 /// [`new_inclusive`]: UniformSampler::new_inclusive
806 /// [`Standard`]: crate::distributions::Standard
807 #[derive(Clone, Copy, Debug)]
808 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
809 pub struct UniformFloat<X> {
810     low: X,
811     scale: X,
812 }
813 
814 macro_rules! uniform_float_impl {
815     ($ty:ty, $uty:ident, $f_scalar:ident, $u_scalar:ident, $bits_to_discard:expr) => {
816         impl SampleUniform for $ty {
817             type Sampler = UniformFloat<$ty>;
818         }
819 
820         impl UniformSampler for UniformFloat<$ty> {
821             type X = $ty;
822 
823             fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
824             where
825                 B1: SampleBorrow<Self::X> + Sized,
826                 B2: SampleBorrow<Self::X> + Sized,
827             {
828                 let low = *low_b.borrow();
829                 let high = *high_b.borrow();
830                 assert!(low.all_lt(high), "Uniform::new called with `low >= high`");
831                 assert!(
832                     low.all_finite() && high.all_finite(),
833                     "Uniform::new called with non-finite boundaries"
834                 );
835                 let max_rand = <$ty>::splat(
836                     (::core::$u_scalar::MAX >> $bits_to_discard).into_float_with_exponent(0) - 1.0,
837                 );
838 
839                 let mut scale = high - low;
840 
841                 loop {
842                     let mask = (scale * max_rand + low).ge_mask(high);
843                     if mask.none() {
844                         break;
845                     }
846                     scale = scale.decrease_masked(mask);
847                 }
848 
849                 debug_assert!(<$ty>::splat(0.0).all_le(scale));
850 
851                 UniformFloat { low, scale }
852             }
853 
854             fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
855             where
856                 B1: SampleBorrow<Self::X> + Sized,
857                 B2: SampleBorrow<Self::X> + Sized,
858             {
859                 let low = *low_b.borrow();
860                 let high = *high_b.borrow();
861                 assert!(
862                     low.all_le(high),
863                     "Uniform::new_inclusive called with `low > high`"
864                 );
865                 assert!(
866                     low.all_finite() && high.all_finite(),
867                     "Uniform::new_inclusive called with non-finite boundaries"
868                 );
869                 let max_rand = <$ty>::splat(
870                     (::core::$u_scalar::MAX >> $bits_to_discard).into_float_with_exponent(0) - 1.0,
871                 );
872 
873                 let mut scale = (high - low) / max_rand;
874 
875                 loop {
876                     let mask = (scale * max_rand + low).gt_mask(high);
877                     if mask.none() {
878                         break;
879                     }
880                     scale = scale.decrease_masked(mask);
881                 }
882 
883                 debug_assert!(<$ty>::splat(0.0).all_le(scale));
884 
885                 UniformFloat { low, scale }
886             }
887 
888             fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
889                 // Generate a value in the range [1, 2)
890                 let value1_2 = (rng.gen::<$uty>() >> $bits_to_discard).into_float_with_exponent(0);
891 
892                 // Get a value in the range [0, 1) in order to avoid
893                 // overflowing into infinity when multiplying with scale
894                 let value0_1 = value1_2 - 1.0;
895 
896                 // We don't use `f64::mul_add`, because it is not available with
897                 // `no_std`. Furthermore, it is slower for some targets (but
898                 // faster for others). However, the order of multiplication and
899                 // addition is important, because on some platforms (e.g. ARM)
900                 // it will be optimized to a single (non-FMA) instruction.
901                 value0_1 * self.scale + self.low
902             }
903 
904             #[inline]
905             fn sample_single<R: Rng + ?Sized, B1, B2>(low_b: B1, high_b: B2, rng: &mut R) -> Self::X
906             where
907                 B1: SampleBorrow<Self::X> + Sized,
908                 B2: SampleBorrow<Self::X> + Sized,
909             {
910                 let low = *low_b.borrow();
911                 let high = *high_b.borrow();
912                 assert!(
913                     low.all_lt(high),
914                     "UniformSampler::sample_single: low >= high"
915                 );
916                 let mut scale = high - low;
917 
918                 loop {
919                     // Generate a value in the range [1, 2)
920                     let value1_2 =
921                         (rng.gen::<$uty>() >> $bits_to_discard).into_float_with_exponent(0);
922 
923                     // Get a value in the range [0, 1) in order to avoid
924                     // overflowing into infinity when multiplying with scale
925                     let value0_1 = value1_2 - 1.0;
926 
927                     // Doing multiply before addition allows some architectures
928                     // to use a single instruction.
929                     let res = value0_1 * scale + low;
930 
931                     debug_assert!(low.all_le(res) || !scale.all_finite());
932                     if res.all_lt(high) {
933                         return res;
934                     }
935 
936                     // This handles a number of edge cases.
937                     // * `low` or `high` is NaN. In this case `scale` and
938                     //   `res` are going to end up as NaN.
939                     // * `low` is negative infinity and `high` is finite.
940                     //   `scale` is going to be infinite and `res` will be
941                     //   NaN.
942                     // * `high` is positive infinity and `low` is finite.
943                     //   `scale` is going to be infinite and `res` will
944                     //   be infinite or NaN (if value0_1 is 0).
945                     // * `low` is negative infinity and `high` is positive
946                     //   infinity. `scale` will be infinite and `res` will
947                     //   be NaN.
948                     // * `low` and `high` are finite, but `high - low`
949                     //   overflows to infinite. `scale` will be infinite
950                     //   and `res` will be infinite or NaN (if value0_1 is 0).
951                     // So if `high` or `low` are non-finite, we are guaranteed
952                     // to fail the `res < high` check above and end up here.
953                     //
954                     // While we technically should check for non-finite `low`
955                     // and `high` before entering the loop, by doing the checks
956                     // here instead, we allow the common case to avoid these
957                     // checks. But we are still guaranteed that if `low` or
958                     // `high` are non-finite we'll end up here and can do the
959                     // appropriate checks.
960                     //
961                     // Likewise `high - low` overflowing to infinity is also
962                     // rare, so handle it here after the common case.
963                     let mask = !scale.finite_mask();
964                     if mask.any() {
965                         assert!(
966                             low.all_finite() && high.all_finite(),
967                             "Uniform::sample_single: low and high must be finite"
968                         );
969                         scale = scale.decrease_masked(mask);
970                     }
971                 }
972             }
973         }
974     };
975 }
976 
977 uniform_float_impl! { f32, u32, f32, u32, 32 - 23 }
978 uniform_float_impl! { f64, u64, f64, u64, 64 - 52 }
979 
980 #[cfg(feature = "simd_support")]
981 uniform_float_impl! { f32x2, u32x2, f32, u32, 32 - 23 }
982 #[cfg(feature = "simd_support")]
983 uniform_float_impl! { f32x4, u32x4, f32, u32, 32 - 23 }
984 #[cfg(feature = "simd_support")]
985 uniform_float_impl! { f32x8, u32x8, f32, u32, 32 - 23 }
986 #[cfg(feature = "simd_support")]
987 uniform_float_impl! { f32x16, u32x16, f32, u32, 32 - 23 }
988 
989 #[cfg(feature = "simd_support")]
990 uniform_float_impl! { f64x2, u64x2, f64, u64, 64 - 52 }
991 #[cfg(feature = "simd_support")]
992 uniform_float_impl! { f64x4, u64x4, f64, u64, 64 - 52 }
993 #[cfg(feature = "simd_support")]
994 uniform_float_impl! { f64x8, u64x8, f64, u64, 64 - 52 }
995 
996 
997 /// The back-end implementing [`UniformSampler`] for `Duration`.
998 ///
999 /// Unless you are implementing [`UniformSampler`] for your own types, this type
1000 /// should not be used directly, use [`Uniform`] instead.
1001 #[derive(Clone, Copy, Debug)]
1002 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
1003 pub struct UniformDuration {
1004     mode: UniformDurationMode,
1005     offset: u32,
1006 }
1007 
1008 #[derive(Debug, Copy, Clone)]
1009 #[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
1010 enum UniformDurationMode {
1011     Small {
1012         secs: u64,
1013         nanos: Uniform<u32>,
1014     },
1015     Medium {
1016         nanos: Uniform<u64>,
1017     },
1018     Large {
1019         max_secs: u64,
1020         max_nanos: u32,
1021         secs: Uniform<u64>,
1022     },
1023 }
1024 
1025 impl SampleUniform for Duration {
1026     type Sampler = UniformDuration;
1027 }
1028 
1029 impl UniformSampler for UniformDuration {
1030     type X = Duration;
1031 
1032     #[inline]
new<B1, B2>(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized,1033     fn new<B1, B2>(low_b: B1, high_b: B2) -> Self
1034     where
1035         B1: SampleBorrow<Self::X> + Sized,
1036         B2: SampleBorrow<Self::X> + Sized,
1037     {
1038         let low = *low_b.borrow();
1039         let high = *high_b.borrow();
1040         assert!(low < high, "Uniform::new called with `low >= high`");
1041         UniformDuration::new_inclusive(low, high - Duration::new(0, 1))
1042     }
1043 
1044     #[inline]
new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self where B1: SampleBorrow<Self::X> + Sized, B2: SampleBorrow<Self::X> + Sized,1045     fn new_inclusive<B1, B2>(low_b: B1, high_b: B2) -> Self
1046     where
1047         B1: SampleBorrow<Self::X> + Sized,
1048         B2: SampleBorrow<Self::X> + Sized,
1049     {
1050         let low = *low_b.borrow();
1051         let high = *high_b.borrow();
1052         assert!(
1053             low <= high,
1054             "Uniform::new_inclusive called with `low > high`"
1055         );
1056 
1057         let low_s = low.as_secs();
1058         let low_n = low.subsec_nanos();
1059         let mut high_s = high.as_secs();
1060         let mut high_n = high.subsec_nanos();
1061 
1062         if high_n < low_n {
1063             high_s -= 1;
1064             high_n += 1_000_000_000;
1065         }
1066 
1067         let mode = if low_s == high_s {
1068             UniformDurationMode::Small {
1069                 secs: low_s,
1070                 nanos: Uniform::new_inclusive(low_n, high_n),
1071             }
1072         } else {
1073             let max = high_s
1074                 .checked_mul(1_000_000_000)
1075                 .and_then(|n| n.checked_add(u64::from(high_n)));
1076 
1077             if let Some(higher_bound) = max {
1078                 let lower_bound = low_s * 1_000_000_000 + u64::from(low_n);
1079                 UniformDurationMode::Medium {
1080                     nanos: Uniform::new_inclusive(lower_bound, higher_bound),
1081                 }
1082             } else {
1083                 // An offset is applied to simplify generation of nanoseconds
1084                 let max_nanos = high_n - low_n;
1085                 UniformDurationMode::Large {
1086                     max_secs: high_s,
1087                     max_nanos,
1088                     secs: Uniform::new_inclusive(low_s, high_s),
1089                 }
1090             }
1091         };
1092         UniformDuration {
1093             mode,
1094             offset: low_n,
1095         }
1096     }
1097 
1098     #[inline]
sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration1099     fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Duration {
1100         match self.mode {
1101             UniformDurationMode::Small { secs, nanos } => {
1102                 let n = nanos.sample(rng);
1103                 Duration::new(secs, n)
1104             }
1105             UniformDurationMode::Medium { nanos } => {
1106                 let nanos = nanos.sample(rng);
1107                 Duration::new(nanos / 1_000_000_000, (nanos % 1_000_000_000) as u32)
1108             }
1109             UniformDurationMode::Large {
1110                 max_secs,
1111                 max_nanos,
1112                 secs,
1113             } => {
1114                 // constant folding means this is at least as fast as `Rng::sample(Range)`
1115                 let nano_range = Uniform::new(0, 1_000_000_000);
1116                 loop {
1117                     let s = secs.sample(rng);
1118                     let n = nano_range.sample(rng);
1119                     if !(s == max_secs && n > max_nanos) {
1120                         let sum = n + self.offset;
1121                         break Duration::new(s, sum);
1122                     }
1123                 }
1124             }
1125         }
1126     }
1127 }
1128 
1129 #[cfg(test)]
1130 mod tests {
1131     use super::*;
1132     use crate::rngs::mock::StepRng;
1133 
1134     #[test]
1135     #[cfg(feature = "serde1")]
test_serialization_uniform_duration()1136     fn test_serialization_uniform_duration() {
1137         let distr = UniformDuration::new(std::time::Duration::from_secs(10), std::time::Duration::from_secs(60));
1138         let de_distr: UniformDuration = bincode::deserialize(&bincode::serialize(&distr).unwrap()).unwrap();
1139         assert_eq!(
1140             distr.offset, de_distr.offset
1141         );
1142         match (distr.mode, de_distr.mode) {
1143             (UniformDurationMode::Small {secs: a_secs, nanos: a_nanos}, UniformDurationMode::Small {secs, nanos}) => {
1144                 assert_eq!(a_secs, secs);
1145 
1146                 assert_eq!(a_nanos.0.low, nanos.0.low);
1147                 assert_eq!(a_nanos.0.range, nanos.0.range);
1148                 assert_eq!(a_nanos.0.z, nanos.0.z);
1149             }
1150             (UniformDurationMode::Medium {nanos: a_nanos} , UniformDurationMode::Medium {nanos}) => {
1151                 assert_eq!(a_nanos.0.low, nanos.0.low);
1152                 assert_eq!(a_nanos.0.range, nanos.0.range);
1153                 assert_eq!(a_nanos.0.z, nanos.0.z);
1154             }
1155             (UniformDurationMode::Large {max_secs:a_max_secs, max_nanos:a_max_nanos, secs:a_secs}, UniformDurationMode::Large {max_secs, max_nanos, secs} ) => {
1156                 assert_eq!(a_max_secs, max_secs);
1157                 assert_eq!(a_max_nanos, max_nanos);
1158 
1159                 assert_eq!(a_secs.0.low, secs.0.low);
1160                 assert_eq!(a_secs.0.range, secs.0.range);
1161                 assert_eq!(a_secs.0.z, secs.0.z);
1162             }
1163             _ => panic!("`UniformDurationMode` was not serialized/deserialized correctly")
1164         }
1165     }
1166 
1167     #[test]
1168     #[cfg(feature = "serde1")]
test_uniform_serialization()1169     fn test_uniform_serialization() {
1170         let unit_box: Uniform<i32>  = Uniform::new(-1, 1);
1171         let de_unit_box: Uniform<i32> = bincode::deserialize(&bincode::serialize(&unit_box).unwrap()).unwrap();
1172 
1173         assert_eq!(unit_box.0.low, de_unit_box.0.low);
1174         assert_eq!(unit_box.0.range, de_unit_box.0.range);
1175         assert_eq!(unit_box.0.z, de_unit_box.0.z);
1176 
1177         let unit_box: Uniform<f32> = Uniform::new(-1., 1.);
1178         let de_unit_box: Uniform<f32> = bincode::deserialize(&bincode::serialize(&unit_box).unwrap()).unwrap();
1179 
1180         assert_eq!(unit_box.0.low, de_unit_box.0.low);
1181         assert_eq!(unit_box.0.scale, de_unit_box.0.scale);
1182     }
1183 
1184     #[should_panic]
1185     #[test]
test_uniform_bad_limits_equal_int()1186     fn test_uniform_bad_limits_equal_int() {
1187         Uniform::new(10, 10);
1188     }
1189 
1190     #[test]
test_uniform_good_limits_equal_int()1191     fn test_uniform_good_limits_equal_int() {
1192         let mut rng = crate::test::rng(804);
1193         let dist = Uniform::new_inclusive(10, 10);
1194         for _ in 0..20 {
1195             assert_eq!(rng.sample(dist), 10);
1196         }
1197     }
1198 
1199     #[should_panic]
1200     #[test]
test_uniform_bad_limits_flipped_int()1201     fn test_uniform_bad_limits_flipped_int() {
1202         Uniform::new(10, 5);
1203     }
1204 
1205     #[test]
1206     #[cfg_attr(miri, ignore)] // Miri is too slow
test_integers()1207     fn test_integers() {
1208         #[cfg(not(target_os = "emscripten"))] use core::{i128, u128};
1209         use core::{i16, i32, i64, i8, isize};
1210         use core::{u16, u32, u64, u8, usize};
1211 
1212         let mut rng = crate::test::rng(251);
1213         macro_rules! t {
1214             ($ty:ident, $v:expr, $le:expr, $lt:expr) => {{
1215                 for &(low, high) in $v.iter() {
1216                     let my_uniform = Uniform::new(low, high);
1217                     for _ in 0..1000 {
1218                         let v: $ty = rng.sample(my_uniform);
1219                         assert!($le(low, v) && $lt(v, high));
1220                     }
1221 
1222                     let my_uniform = Uniform::new_inclusive(low, high);
1223                     for _ in 0..1000 {
1224                         let v: $ty = rng.sample(my_uniform);
1225                         assert!($le(low, v) && $le(v, high));
1226                     }
1227 
1228                     let my_uniform = Uniform::new(&low, high);
1229                     for _ in 0..1000 {
1230                         let v: $ty = rng.sample(my_uniform);
1231                         assert!($le(low, v) && $lt(v, high));
1232                     }
1233 
1234                     let my_uniform = Uniform::new_inclusive(&low, &high);
1235                     for _ in 0..1000 {
1236                         let v: $ty = rng.sample(my_uniform);
1237                         assert!($le(low, v) && $le(v, high));
1238                     }
1239 
1240                     for _ in 0..1000 {
1241                         let v = <$ty as SampleUniform>::Sampler::sample_single(low, high, &mut rng);
1242                         assert!($le(low, v) && $lt(v, high));
1243                     }
1244 
1245                     for _ in 0..1000 {
1246                         let v = <$ty as SampleUniform>::Sampler::sample_single_inclusive(low, high, &mut rng);
1247                         assert!($le(low, v) && $le(v, high));
1248                     }
1249                 }
1250             }};
1251 
1252             // scalar bulk
1253             ($($ty:ident),*) => {{
1254                 $(t!(
1255                     $ty,
1256                     [(0, 10), (10, 127), ($ty::MIN, $ty::MAX)],
1257                     |x, y| x <= y,
1258                     |x, y| x < y
1259                 );)*
1260             }};
1261 
1262             // simd bulk
1263             ($($ty:ident),* => $scalar:ident) => {{
1264                 $(t!(
1265                     $ty,
1266                     [
1267                         ($ty::splat(0), $ty::splat(10)),
1268                         ($ty::splat(10), $ty::splat(127)),
1269                         ($ty::splat($scalar::MIN), $ty::splat($scalar::MAX)),
1270                     ],
1271                     |x: $ty, y| x.le(y).all(),
1272                     |x: $ty, y| x.lt(y).all()
1273                 );)*
1274             }};
1275         }
1276         t!(i8, i16, i32, i64, isize, u8, u16, u32, u64, usize);
1277         #[cfg(not(target_os = "emscripten"))]
1278         t!(i128, u128);
1279 
1280         #[cfg(feature = "simd_support")]
1281         {
1282             t!(u8x2, u8x4, u8x8, u8x16, u8x32, u8x64 => u8);
1283             t!(i8x2, i8x4, i8x8, i8x16, i8x32, i8x64 => i8);
1284             t!(u16x2, u16x4, u16x8, u16x16, u16x32 => u16);
1285             t!(i16x2, i16x4, i16x8, i16x16, i16x32 => i16);
1286             t!(u32x2, u32x4, u32x8, u32x16 => u32);
1287             t!(i32x2, i32x4, i32x8, i32x16 => i32);
1288             t!(u64x2, u64x4, u64x8 => u64);
1289             t!(i64x2, i64x4, i64x8 => i64);
1290         }
1291     }
1292 
1293     #[test]
1294     #[cfg_attr(miri, ignore)] // Miri is too slow
test_char()1295     fn test_char() {
1296         let mut rng = crate::test::rng(891);
1297         let mut max = core::char::from_u32(0).unwrap();
1298         for _ in 0..100 {
1299             let c = rng.gen_range('A'..='Z');
1300             assert!('A' <= c && c <= 'Z');
1301             max = max.max(c);
1302         }
1303         assert_eq!(max, 'Z');
1304         let d = Uniform::new(
1305             core::char::from_u32(0xD7F0).unwrap(),
1306             core::char::from_u32(0xE010).unwrap(),
1307         );
1308         for _ in 0..100 {
1309             let c = d.sample(&mut rng);
1310             assert!((c as u32) < 0xD800 || (c as u32) > 0xDFFF);
1311         }
1312     }
1313 
1314     #[test]
1315     #[cfg_attr(miri, ignore)] // Miri is too slow
test_floats()1316     fn test_floats() {
1317         let mut rng = crate::test::rng(252);
1318         let mut zero_rng = StepRng::new(0, 0);
1319         let mut max_rng = StepRng::new(0xffff_ffff_ffff_ffff, 0);
1320         macro_rules! t {
1321             ($ty:ty, $f_scalar:ident, $bits_shifted:expr) => {{
1322                 let v: &[($f_scalar, $f_scalar)] = &[
1323                     (0.0, 100.0),
1324                     (-1e35, -1e25),
1325                     (1e-35, 1e-25),
1326                     (-1e35, 1e35),
1327                     (<$f_scalar>::from_bits(0), <$f_scalar>::from_bits(3)),
1328                     (-<$f_scalar>::from_bits(10), -<$f_scalar>::from_bits(1)),
1329                     (-<$f_scalar>::from_bits(5), 0.0),
1330                     (-<$f_scalar>::from_bits(7), -0.0),
1331                     (10.0, ::core::$f_scalar::MAX),
1332                     (-100.0, ::core::$f_scalar::MAX),
1333                     (-::core::$f_scalar::MAX / 5.0, ::core::$f_scalar::MAX),
1334                     (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX / 5.0),
1335                     (-::core::$f_scalar::MAX * 0.8, ::core::$f_scalar::MAX * 0.7),
1336                     (-::core::$f_scalar::MAX, ::core::$f_scalar::MAX),
1337                 ];
1338                 for &(low_scalar, high_scalar) in v.iter() {
1339                     for lane in 0..<$ty>::lanes() {
1340                         let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar);
1341                         let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar);
1342                         let my_uniform = Uniform::new(low, high);
1343                         let my_incl_uniform = Uniform::new_inclusive(low, high);
1344                         for _ in 0..100 {
1345                             let v = rng.sample(my_uniform).extract(lane);
1346                             assert!(low_scalar <= v && v < high_scalar);
1347                             let v = rng.sample(my_incl_uniform).extract(lane);
1348                             assert!(low_scalar <= v && v <= high_scalar);
1349                             let v = <$ty as SampleUniform>::Sampler
1350                                 ::sample_single(low, high, &mut rng).extract(lane);
1351                             assert!(low_scalar <= v && v < high_scalar);
1352                         }
1353 
1354                         assert_eq!(
1355                             rng.sample(Uniform::new_inclusive(low, low)).extract(lane),
1356                             low_scalar
1357                         );
1358 
1359                         assert_eq!(zero_rng.sample(my_uniform).extract(lane), low_scalar);
1360                         assert_eq!(zero_rng.sample(my_incl_uniform).extract(lane), low_scalar);
1361                         assert_eq!(<$ty as SampleUniform>::Sampler
1362                             ::sample_single(low, high, &mut zero_rng)
1363                             .extract(lane), low_scalar);
1364                         assert!(max_rng.sample(my_uniform).extract(lane) < high_scalar);
1365                         assert!(max_rng.sample(my_incl_uniform).extract(lane) <= high_scalar);
1366 
1367                         // Don't run this test for really tiny differences between high and low
1368                         // since for those rounding might result in selecting high for a very
1369                         // long time.
1370                         if (high_scalar - low_scalar) > 0.0001 {
1371                             let mut lowering_max_rng = StepRng::new(
1372                                 0xffff_ffff_ffff_ffff,
1373                                 (-1i64 << $bits_shifted) as u64,
1374                             );
1375                             assert!(
1376                                 <$ty as SampleUniform>::Sampler
1377                                     ::sample_single(low, high, &mut lowering_max_rng)
1378                                     .extract(lane) < high_scalar
1379                             );
1380                         }
1381                     }
1382                 }
1383 
1384                 assert_eq!(
1385                     rng.sample(Uniform::new_inclusive(
1386                         ::core::$f_scalar::MAX,
1387                         ::core::$f_scalar::MAX
1388                     )),
1389                     ::core::$f_scalar::MAX
1390                 );
1391                 assert_eq!(
1392                     rng.sample(Uniform::new_inclusive(
1393                         -::core::$f_scalar::MAX,
1394                         -::core::$f_scalar::MAX
1395                     )),
1396                     -::core::$f_scalar::MAX
1397                 );
1398             }};
1399         }
1400 
1401         t!(f32, f32, 32 - 23);
1402         t!(f64, f64, 64 - 52);
1403         #[cfg(feature = "simd_support")]
1404         {
1405             t!(f32x2, f32, 32 - 23);
1406             t!(f32x4, f32, 32 - 23);
1407             t!(f32x8, f32, 32 - 23);
1408             t!(f32x16, f32, 32 - 23);
1409             t!(f64x2, f64, 64 - 52);
1410             t!(f64x4, f64, 64 - 52);
1411             t!(f64x8, f64, 64 - 52);
1412         }
1413     }
1414 
1415     #[test]
1416     #[cfg(all(
1417         feature = "std",
1418         not(target_arch = "wasm32"),
1419         not(target_arch = "asmjs")
1420     ))]
test_float_assertions()1421     fn test_float_assertions() {
1422         use super::SampleUniform;
1423         use std::panic::catch_unwind;
1424         fn range<T: SampleUniform>(low: T, high: T) {
1425             let mut rng = crate::test::rng(253);
1426             T::Sampler::sample_single(low, high, &mut rng);
1427         }
1428 
1429         macro_rules! t {
1430             ($ty:ident, $f_scalar:ident) => {{
1431                 let v: &[($f_scalar, $f_scalar)] = &[
1432                     (::std::$f_scalar::NAN, 0.0),
1433                     (1.0, ::std::$f_scalar::NAN),
1434                     (::std::$f_scalar::NAN, ::std::$f_scalar::NAN),
1435                     (1.0, 0.5),
1436                     (::std::$f_scalar::MAX, -::std::$f_scalar::MAX),
1437                     (::std::$f_scalar::INFINITY, ::std::$f_scalar::INFINITY),
1438                     (
1439                         ::std::$f_scalar::NEG_INFINITY,
1440                         ::std::$f_scalar::NEG_INFINITY,
1441                     ),
1442                     (::std::$f_scalar::NEG_INFINITY, 5.0),
1443                     (5.0, ::std::$f_scalar::INFINITY),
1444                     (::std::$f_scalar::NAN, ::std::$f_scalar::INFINITY),
1445                     (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::NAN),
1446                     (::std::$f_scalar::NEG_INFINITY, ::std::$f_scalar::INFINITY),
1447                 ];
1448                 for &(low_scalar, high_scalar) in v.iter() {
1449                     for lane in 0..<$ty>::lanes() {
1450                         let low = <$ty>::splat(0.0 as $f_scalar).replace(lane, low_scalar);
1451                         let high = <$ty>::splat(1.0 as $f_scalar).replace(lane, high_scalar);
1452                         assert!(catch_unwind(|| range(low, high)).is_err());
1453                         assert!(catch_unwind(|| Uniform::new(low, high)).is_err());
1454                         assert!(catch_unwind(|| Uniform::new_inclusive(low, high)).is_err());
1455                         assert!(catch_unwind(|| range(low, low)).is_err());
1456                         assert!(catch_unwind(|| Uniform::new(low, low)).is_err());
1457                     }
1458                 }
1459             }};
1460         }
1461 
1462         t!(f32, f32);
1463         t!(f64, f64);
1464         #[cfg(feature = "simd_support")]
1465         {
1466             t!(f32x2, f32);
1467             t!(f32x4, f32);
1468             t!(f32x8, f32);
1469             t!(f32x16, f32);
1470             t!(f64x2, f64);
1471             t!(f64x4, f64);
1472             t!(f64x8, f64);
1473         }
1474     }
1475 
1476 
1477     #[test]
1478     #[cfg_attr(miri, ignore)] // Miri is too slow
test_durations()1479     fn test_durations() {
1480         #[cfg(not(feature = "std"))] use core::time::Duration;
1481         #[cfg(feature = "std")] use std::time::Duration;
1482 
1483         let mut rng = crate::test::rng(253);
1484 
1485         let v = &[
1486             (Duration::new(10, 50000), Duration::new(100, 1234)),
1487             (Duration::new(0, 100), Duration::new(1, 50)),
1488             (
1489                 Duration::new(0, 0),
1490                 Duration::new(u64::max_value(), 999_999_999),
1491             ),
1492         ];
1493         for &(low, high) in v.iter() {
1494             let my_uniform = Uniform::new(low, high);
1495             for _ in 0..1000 {
1496                 let v = rng.sample(my_uniform);
1497                 assert!(low <= v && v < high);
1498             }
1499         }
1500     }
1501 
1502     #[test]
test_custom_uniform()1503     fn test_custom_uniform() {
1504         use crate::distributions::uniform::{
1505             SampleBorrow, SampleUniform, UniformFloat, UniformSampler,
1506         };
1507         #[derive(Clone, Copy, PartialEq, PartialOrd)]
1508         struct MyF32 {
1509             x: f32,
1510         }
1511         #[derive(Clone, Copy, Debug)]
1512         struct UniformMyF32(UniformFloat<f32>);
1513         impl UniformSampler for UniformMyF32 {
1514             type X = MyF32;
1515 
1516             fn new<B1, B2>(low: B1, high: B2) -> Self
1517             where
1518                 B1: SampleBorrow<Self::X> + Sized,
1519                 B2: SampleBorrow<Self::X> + Sized,
1520             {
1521                 UniformMyF32(UniformFloat::<f32>::new(low.borrow().x, high.borrow().x))
1522             }
1523 
1524             fn new_inclusive<B1, B2>(low: B1, high: B2) -> Self
1525             where
1526                 B1: SampleBorrow<Self::X> + Sized,
1527                 B2: SampleBorrow<Self::X> + Sized,
1528             {
1529                 UniformSampler::new(low, high)
1530             }
1531 
1532             fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Self::X {
1533                 MyF32 {
1534                     x: self.0.sample(rng),
1535                 }
1536             }
1537         }
1538         impl SampleUniform for MyF32 {
1539             type Sampler = UniformMyF32;
1540         }
1541 
1542         let (low, high) = (MyF32 { x: 17.0f32 }, MyF32 { x: 22.0f32 });
1543         let uniform = Uniform::new(low, high);
1544         let mut rng = crate::test::rng(804);
1545         for _ in 0..100 {
1546             let x: MyF32 = rng.sample(uniform);
1547             assert!(low <= x && x < high);
1548         }
1549     }
1550 
1551     #[test]
test_uniform_from_std_range()1552     fn test_uniform_from_std_range() {
1553         let r = Uniform::from(2u32..7);
1554         assert_eq!(r.0.low, 2);
1555         assert_eq!(r.0.range, 5);
1556         let r = Uniform::from(2.0f64..7.0);
1557         assert_eq!(r.0.low, 2.0);
1558         assert_eq!(r.0.scale, 5.0);
1559     }
1560 
1561     #[test]
test_uniform_from_std_range_inclusive()1562     fn test_uniform_from_std_range_inclusive() {
1563         let r = Uniform::from(2u32..=6);
1564         assert_eq!(r.0.low, 2);
1565         assert_eq!(r.0.range, 5);
1566         let r = Uniform::from(2.0f64..=7.0);
1567         assert_eq!(r.0.low, 2.0);
1568         assert!(r.0.scale > 5.0);
1569         assert!(r.0.scale < 5.0 + 1e-14);
1570     }
1571 
1572     #[test]
value_stability()1573     fn value_stability() {
1574         fn test_samples<T: SampleUniform + Copy + core::fmt::Debug + PartialEq>(
1575             lb: T, ub: T, expected_single: &[T], expected_multiple: &[T],
1576         ) where Uniform<T>: Distribution<T> {
1577             let mut rng = crate::test::rng(897);
1578             let mut buf = [lb; 3];
1579 
1580             for x in &mut buf {
1581                 *x = T::Sampler::sample_single(lb, ub, &mut rng);
1582             }
1583             assert_eq!(&buf, expected_single);
1584 
1585             let distr = Uniform::new(lb, ub);
1586             for x in &mut buf {
1587                 *x = rng.sample(&distr);
1588             }
1589             assert_eq!(&buf, expected_multiple);
1590         }
1591 
1592         // We test on a sub-set of types; possibly we should do more.
1593         // TODO: SIMD types
1594 
1595         test_samples(11u8, 219, &[17, 66, 214], &[181, 93, 165]);
1596         test_samples(11u32, 219, &[17, 66, 214], &[181, 93, 165]);
1597 
1598         test_samples(0f32, 1e-2f32, &[0.0003070104, 0.0026630748, 0.00979833], &[
1599             0.008194133,
1600             0.00398172,
1601             0.007428536,
1602         ]);
1603         test_samples(
1604             -1e10f64,
1605             1e10f64,
1606             &[-4673848682.871551, 6388267422.932352, 4857075081.198343],
1607             &[1173375212.1808167, 1917642852.109581, 2365076174.3153973],
1608         );
1609 
1610         test_samples(
1611             Duration::new(2, 0),
1612             Duration::new(4, 0),
1613             &[
1614                 Duration::new(2, 532615131),
1615                 Duration::new(3, 638826742),
1616                 Duration::new(3, 485707508),
1617             ],
1618             &[
1619                 Duration::new(3, 117337521),
1620                 Duration::new(3, 191764285),
1621                 Duration::new(3, 236507617),
1622             ],
1623         );
1624     }
1625 }
1626