1 // Copyright 2018 Developers of the Rand project.
2 // Copyright 2013-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 //! Utilities for random number generation
11 //!
12 //! Rand provides utilities to generate random numbers, to convert them to
13 //! useful types and distributions, and some randomness-related algorithms.
14 //!
15 //! # Quick Start
16 //!
17 //! To get you started quickly, the easiest and highest-level way to get
18 //! a random value is to use [`random()`]; alternatively you can use
19 //! [`thread_rng()`]. The [`Rng`] trait provides a useful API on all RNGs, while
20 //! the [`distributions`] and [`seq`] modules provide further
21 //! functionality on top of RNGs.
22 //!
23 //! ```
24 //! use rand::prelude::*;
25 //!
26 //! if rand::random() { // generates a boolean
27 //!     // Try printing a random unicode code point (probably a bad idea)!
28 //!     println!("char: {}", rand::random::<char>());
29 //! }
30 //!
31 //! let mut rng = rand::thread_rng();
32 //! let y: f64 = rng.gen(); // generates a float between 0 and 1
33 //!
34 //! let mut nums: Vec<i32> = (1..100).collect();
35 //! nums.shuffle(&mut rng);
36 //! ```
37 //!
38 //! # The Book
39 //!
40 //! For the user guide and futher documentation, please read
41 //! [The Rust Rand Book](https://rust-random.github.io/book).
42 
43 
44 #![doc(html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
45        html_favicon_url = "https://www.rust-lang.org/favicon.ico",
46        html_root_url = "https://rust-random.github.io/rand/")]
47 
48 #![deny(missing_docs)]
49 #![deny(missing_debug_implementations)]
50 #![doc(test(attr(allow(unused_variables), deny(warnings))))]
51 
52 #![cfg_attr(not(feature="std"), no_std)]
53 #![cfg_attr(all(feature="alloc", not(feature="std")), feature(alloc))]
54 #![cfg_attr(all(feature="simd_support", feature="nightly"), feature(stdsimd))]
55 
56 #[cfg(all(feature="alloc", not(feature="std")))]
57 extern crate alloc;
58 
59 #[cfg(feature = "getrandom")]
60 use getrandom_package as getrandom;
61 
62 #[allow(unused)]
63 macro_rules! trace { ($($x:tt)*) => (
64     #[cfg(feature = "log")] {
65         log::trace!($($x)*)
66     }
67 ) }
68 #[allow(unused)]
69 macro_rules! debug { ($($x:tt)*) => (
70     #[cfg(feature = "log")] {
71         log::debug!($($x)*)
72     }
73 ) }
74 #[allow(unused)]
75 macro_rules! info { ($($x:tt)*) => (
76     #[cfg(feature = "log")] {
77         log::info!($($x)*)
78     }
79 ) }
80 #[allow(unused)]
81 macro_rules! warn { ($($x:tt)*) => (
82     #[cfg(feature = "log")] {
83         log::warn!($($x)*)
84     }
85 ) }
86 #[allow(unused)]
87 macro_rules! error { ($($x:tt)*) => (
88     #[cfg(feature = "log")] {
89         log::error!($($x)*)
90     }
91 ) }
92 
93 // Re-exports from rand_core
94 pub use rand_core::{RngCore, CryptoRng, SeedableRng, Error};
95 
96 // Public exports
97 #[cfg(feature="std")] pub use crate::rngs::thread::thread_rng;
98 
99 // Public modules
100 pub mod distributions;
101 pub mod prelude;
102 pub mod rngs;
103 pub mod seq;
104 
105 
106 use core::{mem, slice};
107 use core::num::Wrapping;
108 use crate::distributions::{Distribution, Standard};
109 use crate::distributions::uniform::{SampleUniform, UniformSampler, SampleBorrow};
110 
111 /// An automatically-implemented extension trait on [`RngCore`] providing high-level
112 /// generic methods for sampling values and other convenience methods.
113 ///
114 /// This is the primary trait to use when generating random values.
115 ///
116 /// # Generic usage
117 ///
118 /// The basic pattern is `fn foo<R: Rng + ?Sized>(rng: &mut R)`. Some
119 /// things are worth noting here:
120 ///
121 /// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no
122 ///   difference whether we use `R: Rng` or `R: RngCore`.
123 /// - The `+ ?Sized` un-bounding allows functions to be called directly on
124 ///   type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without
125 ///   this it would be necessary to write `foo(&mut r)`.
126 ///
127 /// An alternative pattern is possible: `fn foo<R: Rng>(rng: R)`. This has some
128 /// trade-offs. It allows the argument to be consumed directly without a `&mut`
129 /// (which is how `from_rng(thread_rng())` works); also it still works directly
130 /// on references (including type-erased references). Unfortunately within the
131 /// function `foo` it is not known whether `rng` is a reference type or not,
132 /// hence many uses of `rng` require an extra reference, either explicitly
133 /// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the
134 /// optimiser can remove redundant references later.
135 ///
136 /// Example:
137 ///
138 /// ```
139 /// # use rand::thread_rng;
140 /// use rand::Rng;
141 ///
142 /// fn foo<R: Rng + ?Sized>(rng: &mut R) -> f32 {
143 ///     rng.gen()
144 /// }
145 ///
146 /// # let v = foo(&mut thread_rng());
147 /// ```
148 pub trait Rng: RngCore {
149     /// Return a random value supporting the [`Standard`] distribution.
150     ///
151     /// # Example
152     ///
153     /// ```
154     /// use rand::{thread_rng, Rng};
155     ///
156     /// let mut rng = thread_rng();
157     /// let x: u32 = rng.gen();
158     /// println!("{}", x);
159     /// println!("{:?}", rng.gen::<(f64, bool)>());
160     /// ```
161     ///
162     /// # Arrays and tuples
163     ///
164     /// The `rng.gen()` method is able to generate arrays (up to 32 elements)
165     /// and tuples (up to 12 elements), so long as all element types can be
166     /// generated.
167     ///
168     /// For arrays of integers, especially for those with small element types
169     /// (< 64 bit), it will likely be faster to instead use [`Rng::fill`].
170     ///
171     /// ```
172     /// use rand::{thread_rng, Rng};
173     ///
174     /// let mut rng = thread_rng();
175     /// let tuple: (u8, i32, char) = rng.gen(); // arbitrary tuple support
176     ///
177     /// let arr1: [f32; 32] = rng.gen();        // array construction
178     /// let mut arr2 = [0u8; 128];
179     /// rng.fill(&mut arr2);                    // array fill
180     /// ```
181     ///
182     /// [`Standard`]: distributions::Standard
183     #[inline]
gen<T>(&mut self) -> T where Standard: Distribution<T>184     fn gen<T>(&mut self) -> T
185     where Standard: Distribution<T> {
186         Standard.sample(self)
187     }
188 
189     /// Generate a random value in the range [`low`, `high`), i.e. inclusive of
190     /// `low` and exclusive of `high`.
191     ///
192     /// This function is optimised for the case that only a single sample is
193     /// made from the given range. See also the [`Uniform`] distribution
194     /// type which may be faster if sampling from the same range repeatedly.
195     ///
196     /// # Panics
197     ///
198     /// Panics if `low >= high`.
199     ///
200     /// # Example
201     ///
202     /// ```
203     /// use rand::{thread_rng, Rng};
204     ///
205     /// let mut rng = thread_rng();
206     /// let n: u32 = rng.gen_range(0, 10);
207     /// println!("{}", n);
208     /// let m: f64 = rng.gen_range(-40.0f64, 1.3e5f64);
209     /// println!("{}", m);
210     /// ```
211     ///
212     /// [`Uniform`]: distributions::uniform::Uniform
gen_range<T: SampleUniform, B1, B2>(&mut self, low: B1, high: B2) -> T where B1: SampleBorrow<T> + Sized, B2: SampleBorrow<T> + Sized,213     fn gen_range<T: SampleUniform, B1, B2>(&mut self, low: B1, high: B2) -> T
214     where
215         B1: SampleBorrow<T> + Sized,
216         B2: SampleBorrow<T> + Sized,
217     {
218         T::Sampler::sample_single(low, high, self)
219     }
220 
221     /// Sample a new value, using the given distribution.
222     ///
223     /// ### Example
224     ///
225     /// ```
226     /// use rand::{thread_rng, Rng};
227     /// use rand::distributions::Uniform;
228     ///
229     /// let mut rng = thread_rng();
230     /// let x = rng.sample(Uniform::new(10u32, 15));
231     /// // Type annotation requires two types, the type and distribution; the
232     /// // distribution can be inferred.
233     /// let y = rng.sample::<u16, _>(Uniform::new(10, 15));
234     /// ```
sample<T, D: Distribution<T>>(&mut self, distr: D) -> T235     fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
236         distr.sample(self)
237     }
238 
239     /// Create an iterator that generates values using the given distribution.
240     ///
241     /// Note that this function takes its arguments by value. This works since
242     /// `(&mut R): Rng where R: Rng` and
243     /// `(&D): Distribution where D: Distribution`,
244     /// however borrowing is not automatic hence `rng.sample_iter(...)` may
245     /// need to be replaced with `(&mut rng).sample_iter(...)`.
246     ///
247     /// # Example
248     ///
249     /// ```
250     /// use rand::{thread_rng, Rng};
251     /// use rand::distributions::{Alphanumeric, Uniform, Standard};
252     ///
253     /// let rng = thread_rng();
254     ///
255     /// // Vec of 16 x f32:
256     /// let v: Vec<f32> = rng.sample_iter(Standard).take(16).collect();
257     ///
258     /// // String:
259     /// let s: String = rng.sample_iter(Alphanumeric).take(7).collect();
260     ///
261     /// // Combined values
262     /// println!("{:?}", rng.sample_iter(Standard).take(5)
263     ///                              .collect::<Vec<(f64, bool)>>());
264     ///
265     /// // Dice-rolling:
266     /// let die_range = Uniform::new_inclusive(1, 6);
267     /// let mut roll_die = rng.sample_iter(die_range);
268     /// while roll_die.next().unwrap() != 6 {
269     ///     println!("Not a 6; rolling again!");
270     /// }
271     /// ```
sample_iter<T, D>(self, distr: D) -> distributions::DistIter<D, Self, T> where D: Distribution<T>, Self: Sized272     fn sample_iter<T, D>(self, distr: D) -> distributions::DistIter<D, Self, T>
273     where D: Distribution<T>, Self: Sized {
274         distr.sample_iter(self)
275     }
276 
277     /// Fill `dest` entirely with random bytes (uniform value distribution),
278     /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
279     /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
280     ///
281     /// On big-endian platforms this performs byte-swapping to ensure
282     /// portability of results from reproducible generators.
283     ///
284     /// This uses [`fill_bytes`] internally which may handle some RNG errors
285     /// implicitly (e.g. waiting if the OS generator is not ready), but panics
286     /// on other errors. See also [`try_fill`] which returns errors.
287     ///
288     /// # Example
289     ///
290     /// ```
291     /// use rand::{thread_rng, Rng};
292     ///
293     /// let mut arr = [0i8; 20];
294     /// thread_rng().fill(&mut arr[..]);
295     /// ```
296     ///
297     /// [`fill_bytes`]: RngCore::fill_bytes
298     /// [`try_fill`]: Rng::try_fill
fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T)299     fn fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) {
300         self.fill_bytes(dest.as_byte_slice_mut());
301         dest.to_le();
302     }
303 
304     /// Fill `dest` entirely with random bytes (uniform value distribution),
305     /// where `dest` is any type supporting [`AsByteSliceMut`], namely slices
306     /// and arrays over primitive integer types (`i8`, `i16`, `u32`, etc.).
307     ///
308     /// On big-endian platforms this performs byte-swapping to ensure
309     /// portability of results from reproducible generators.
310     ///
311     /// This is identical to [`fill`] except that it uses [`try_fill_bytes`]
312     /// internally and forwards RNG errors.
313     ///
314     /// # Example
315     ///
316     /// ```
317     /// # use rand::Error;
318     /// use rand::{thread_rng, Rng};
319     ///
320     /// # fn try_inner() -> Result<(), Error> {
321     /// let mut arr = [0u64; 4];
322     /// thread_rng().try_fill(&mut arr[..])?;
323     /// # Ok(())
324     /// # }
325     ///
326     /// # try_inner().unwrap()
327     /// ```
328     ///
329     /// [`try_fill_bytes`]: RngCore::try_fill_bytes
330     /// [`fill`]: Rng::fill
try_fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error>331     fn try_fill<T: AsByteSliceMut + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> {
332         self.try_fill_bytes(dest.as_byte_slice_mut())?;
333         dest.to_le();
334         Ok(())
335     }
336 
337     /// Return a bool with a probability `p` of being true.
338     ///
339     /// See also the [`Bernoulli`] distribution, which may be faster if
340     /// sampling from the same probability repeatedly.
341     ///
342     /// # Example
343     ///
344     /// ```
345     /// use rand::{thread_rng, Rng};
346     ///
347     /// let mut rng = thread_rng();
348     /// println!("{}", rng.gen_bool(1.0 / 3.0));
349     /// ```
350     ///
351     /// # Panics
352     ///
353     /// If `p < 0` or `p > 1`.
354     ///
355     /// [`Bernoulli`]: distributions::bernoulli::Bernoulli
356     #[inline]
gen_bool(&mut self, p: f64) -> bool357     fn gen_bool(&mut self, p: f64) -> bool {
358         let d = distributions::Bernoulli::new(p).unwrap();
359         self.sample(d)
360     }
361 
362     /// Return a bool with a probability of `numerator/denominator` of being
363     /// true. I.e. `gen_ratio(2, 3)` has chance of 2 in 3, or about 67%, of
364     /// returning true. If `numerator == denominator`, then the returned value
365     /// is guaranteed to be `true`. If `numerator == 0`, then the returned
366     /// value is guaranteed to be `false`.
367     ///
368     /// See also the [`Bernoulli`] distribution, which may be faster if
369     /// sampling from the same `numerator` and `denominator` repeatedly.
370     ///
371     /// # Panics
372     ///
373     /// If `denominator == 0` or `numerator > denominator`.
374     ///
375     /// # Example
376     ///
377     /// ```
378     /// use rand::{thread_rng, Rng};
379     ///
380     /// let mut rng = thread_rng();
381     /// println!("{}", rng.gen_ratio(2, 3));
382     /// ```
383     ///
384     /// [`Bernoulli`]: distributions::bernoulli::Bernoulli
385     #[inline]
gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool386     fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
387         let d = distributions::Bernoulli::from_ratio(numerator, denominator).unwrap();
388         self.sample(d)
389     }
390 }
391 
392 impl<R: RngCore + ?Sized> Rng for R {}
393 
394 /// Trait for casting types to byte slices
395 ///
396 /// This is used by the [`Rng::fill`] and [`Rng::try_fill`] methods.
397 pub trait AsByteSliceMut {
398     /// Return a mutable reference to self as a byte slice
as_byte_slice_mut(&mut self) -> &mut [u8]399     fn as_byte_slice_mut(&mut self) -> &mut [u8];
400 
401     /// Call `to_le` on each element (i.e. byte-swap on Big Endian platforms).
to_le(&mut self)402     fn to_le(&mut self);
403 }
404 
405 impl AsByteSliceMut for [u8] {
as_byte_slice_mut(&mut self) -> &mut [u8]406     fn as_byte_slice_mut(&mut self) -> &mut [u8] {
407         self
408     }
409 
to_le(&mut self)410     fn to_le(&mut self) {}
411 }
412 
413 macro_rules! impl_as_byte_slice {
414     () => {};
415     ($t:ty) => {
416         impl AsByteSliceMut for [$t] {
417             fn as_byte_slice_mut(&mut self) -> &mut [u8] {
418                 if self.len() == 0 {
419                     unsafe {
420                         // must not use null pointer
421                         slice::from_raw_parts_mut(0x1 as *mut u8, 0)
422                     }
423                 } else {
424                     unsafe {
425                         slice::from_raw_parts_mut(self.as_mut_ptr()
426                             as *mut u8,
427                             self.len() * mem::size_of::<$t>()
428                         )
429                     }
430                 }
431             }
432 
433             fn to_le(&mut self) {
434                 for x in self {
435                     *x = x.to_le();
436                 }
437             }
438         }
439 
440         impl AsByteSliceMut for [Wrapping<$t>] {
441             fn as_byte_slice_mut(&mut self) -> &mut [u8] {
442                 if self.len() == 0 {
443                     unsafe {
444                         // must not use null pointer
445                         slice::from_raw_parts_mut(0x1 as *mut u8, 0)
446                     }
447                 } else {
448                     unsafe {
449                         slice::from_raw_parts_mut(self.as_mut_ptr()
450                             as *mut u8,
451                             self.len() * mem::size_of::<$t>()
452                         )
453                     }
454                 }
455             }
456 
457             fn to_le(&mut self) {
458                 for x in self {
459                     *x = Wrapping(x.0.to_le());
460                 }
461             }
462         }
463     };
464     ($t:ty, $($tt:ty,)*) => {
465         impl_as_byte_slice!($t);
466         // TODO: this could replace above impl once Rust #32463 is fixed
467         // impl_as_byte_slice!(Wrapping<$t>);
468         impl_as_byte_slice!($($tt,)*);
469     }
470 }
471 
472 impl_as_byte_slice!(u16, u32, u64, usize,);
473 #[cfg(not(target_os = "emscripten"))] impl_as_byte_slice!(u128);
474 impl_as_byte_slice!(i8, i16, i32, i64, isize,);
475 #[cfg(not(target_os = "emscripten"))] impl_as_byte_slice!(i128);
476 
477 macro_rules! impl_as_byte_slice_arrays {
478     ($n:expr,) => {};
479     ($n:expr, $N:ident) => {
480         impl<T> AsByteSliceMut for [T; $n] where [T]: AsByteSliceMut {
481             fn as_byte_slice_mut(&mut self) -> &mut [u8] {
482                 self[..].as_byte_slice_mut()
483             }
484 
485             fn to_le(&mut self) {
486                 self[..].to_le()
487             }
488         }
489     };
490     ($n:expr, $N:ident, $($NN:ident,)*) => {
491         impl_as_byte_slice_arrays!($n, $N);
492         impl_as_byte_slice_arrays!($n - 1, $($NN,)*);
493     };
494     (!div $n:expr,) => {};
495     (!div $n:expr, $N:ident, $($NN:ident,)*) => {
496         impl_as_byte_slice_arrays!($n, $N);
497         impl_as_byte_slice_arrays!(!div $n / 2, $($NN,)*);
498     };
499 }
500 impl_as_byte_slice_arrays!(32, N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,N,);
501 impl_as_byte_slice_arrays!(!div 4096, N,N,N,N,N,N,N,);
502 
503 /// Generates a random value using the thread-local random number generator.
504 ///
505 /// This is simply a shortcut for `thread_rng().gen()`. See [`thread_rng`] for
506 /// documentation of the entropy source and [`Standard`] for documentation of
507 /// distributions and type-specific generation.
508 ///
509 /// # Examples
510 ///
511 /// ```
512 /// let x = rand::random::<u8>();
513 /// println!("{}", x);
514 ///
515 /// let y = rand::random::<f64>();
516 /// println!("{}", y);
517 ///
518 /// if rand::random() { // generates a boolean
519 ///     println!("Better lucky than good!");
520 /// }
521 /// ```
522 ///
523 /// If you're calling `random()` in a loop, caching the generator as in the
524 /// following example can increase performance.
525 ///
526 /// ```
527 /// use rand::Rng;
528 ///
529 /// let mut v = vec![1, 2, 3];
530 ///
531 /// for x in v.iter_mut() {
532 ///     *x = rand::random()
533 /// }
534 ///
535 /// // can be made faster by caching thread_rng
536 ///
537 /// let mut rng = rand::thread_rng();
538 ///
539 /// for x in v.iter_mut() {
540 ///     *x = rng.gen();
541 /// }
542 /// ```
543 ///
544 /// [`Standard`]: distributions::Standard
545 #[cfg(feature="std")]
546 #[inline]
random<T>() -> T where Standard: Distribution<T>547 pub fn random<T>() -> T
548 where Standard: Distribution<T> {
549     thread_rng().gen()
550 }
551 
552 #[cfg(test)]
553 mod test {
554     use crate::rngs::mock::StepRng;
555     use super::*;
556     #[cfg(all(not(feature="std"), feature="alloc"))] use alloc::boxed::Box;
557 
558     /// Construct a deterministic RNG with the given seed
rng(seed: u64) -> impl RngCore559     pub fn rng(seed: u64) -> impl RngCore {
560         // For tests, we want a statistically good, fast, reproducible RNG.
561         // PCG32 will do fine, and will be easy to embed if we ever need to.
562         const INC: u64 = 11634580027462260723;
563         rand_pcg::Pcg32::new(seed, INC)
564     }
565 
566     #[test]
test_fill_bytes_default()567     fn test_fill_bytes_default() {
568         let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0);
569 
570         // check every remainder mod 8, both in small and big vectors.
571         let lengths = [0, 1, 2, 3, 4, 5, 6, 7,
572                        80, 81, 82, 83, 84, 85, 86, 87];
573         for &n in lengths.iter() {
574             let mut buffer = [0u8; 87];
575             let v = &mut buffer[0..n];
576             r.fill_bytes(v);
577 
578             // use this to get nicer error messages.
579             for (i, &byte) in v.iter().enumerate() {
580                 if byte == 0 {
581                     panic!("byte {} of {} is zero", i, n)
582                 }
583             }
584         }
585     }
586 
587     #[test]
test_fill()588     fn test_fill() {
589         let x = 9041086907909331047;    // a random u64
590         let mut rng = StepRng::new(x, 0);
591 
592         // Convert to byte sequence and back to u64; byte-swap twice if BE.
593         let mut array = [0u64; 2];
594         rng.fill(&mut array[..]);
595         assert_eq!(array, [x, x]);
596         assert_eq!(rng.next_u64(), x);
597 
598         // Convert to bytes then u32 in LE order
599         let mut array = [0u32; 2];
600         rng.fill(&mut array[..]);
601         assert_eq!(array, [x as u32, (x >> 32) as u32]);
602         assert_eq!(rng.next_u32(), x as u32);
603 
604         // Check equivalence using wrapped arrays
605         let mut warray = [Wrapping(0u32); 2];
606         rng.fill(&mut warray[..]);
607         assert_eq!(array[0], warray[0].0);
608         assert_eq!(array[1], warray[1].0);
609     }
610 
611     #[test]
test_fill_empty()612     fn test_fill_empty() {
613         let mut array = [0u32; 0];
614         let mut rng = StepRng::new(0, 1);
615         rng.fill(&mut array);
616         rng.fill(&mut array[..]);
617     }
618 
619     #[test]
test_gen_range()620     fn test_gen_range() {
621         let mut r = rng(101);
622         for _ in 0..1000 {
623             let a = r.gen_range(-4711, 17);
624             assert!(a >= -4711 && a < 17);
625             let a = r.gen_range(-3i8, 42);
626             assert!(a >= -3i8 && a < 42i8);
627             let a = r.gen_range(&10u16, 99);
628             assert!(a >= 10u16 && a < 99u16);
629             let a = r.gen_range(-100i32, &2000);
630             assert!(a >= -100i32 && a < 2000i32);
631             let a = r.gen_range(&12u32, &24u32);
632             assert!(a >= 12u32 && a < 24u32);
633 
634             assert_eq!(r.gen_range(0u32, 1), 0u32);
635             assert_eq!(r.gen_range(-12i64, -11), -12i64);
636             assert_eq!(r.gen_range(3_000_000, 3_000_001), 3_000_000);
637         }
638     }
639 
640     #[test]
641     #[should_panic]
test_gen_range_panic_int()642     fn test_gen_range_panic_int() {
643         let mut r = rng(102);
644         r.gen_range(5, -2);
645     }
646 
647     #[test]
648     #[should_panic]
test_gen_range_panic_usize()649     fn test_gen_range_panic_usize() {
650         let mut r = rng(103);
651         r.gen_range(5, 2);
652     }
653 
654     #[test]
test_gen_bool()655     fn test_gen_bool() {
656         let mut r = rng(105);
657         for _ in 0..5 {
658             assert_eq!(r.gen_bool(0.0), false);
659             assert_eq!(r.gen_bool(1.0), true);
660         }
661     }
662 
663     #[test]
test_rng_trait_object()664     fn test_rng_trait_object() {
665         use crate::distributions::{Distribution, Standard};
666         let mut rng = rng(109);
667         let mut r = &mut rng as &mut dyn RngCore;
668         r.next_u32();
669         r.gen::<i32>();
670         assert_eq!(r.gen_range(0, 1), 0);
671         let _c: u8 = Standard.sample(&mut r);
672     }
673 
674     #[test]
675     #[cfg(feature="alloc")]
test_rng_boxed_trait()676     fn test_rng_boxed_trait() {
677         use crate::distributions::{Distribution, Standard};
678         let rng = rng(110);
679         let mut r = Box::new(rng) as Box<dyn RngCore>;
680         r.next_u32();
681         r.gen::<i32>();
682         assert_eq!(r.gen_range(0, 1), 0);
683         let _c: u8 = Standard.sample(&mut r);
684     }
685 
686     #[test]
687     #[cfg(feature="std")]
test_random()688     fn test_random() {
689         // not sure how to test this aside from just getting some values
690         let _n : usize = random();
691         let _f : f32 = random();
692         let _o : Option<Option<i8>> = random();
693         let _many : ((),
694                      (usize,
695                       isize,
696                       Option<(u32, (bool,))>),
697                      (u8, i8, u16, i16, u32, i32, u64, i64),
698                      (f32, (f64, (f64,)))) = random();
699     }
700 
701     #[test]
702     #[cfg(not(miri))] // Miri is too slow
test_gen_ratio_average()703     fn test_gen_ratio_average() {
704         const NUM: u32 = 3;
705         const DENOM: u32 = 10;
706         const N: u32 = 100_000;
707 
708         let mut sum: u32 = 0;
709         let mut rng = rng(111);
710         for _ in 0..N {
711             if rng.gen_ratio(NUM, DENOM) {
712                 sum += 1;
713             }
714         }
715         // Have Binomial(N, NUM/DENOM) distribution
716         let expected = (NUM * N) / DENOM;   // exact integer
717         assert!(((sum - expected) as i32).abs() < 500);
718     }
719 }
720