• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 //! [`Rng`] trait
11 
12 use rand_core::{Error, RngCore};
13 use crate::distributions::uniform::{SampleRange, SampleUniform};
14 use crate::distributions::{self, Distribution, Standard};
15 use core::num::Wrapping;
16 use core::{mem, slice};
17 
18 /// An automatically-implemented extension trait on [`RngCore`] providing high-level
19 /// generic methods for sampling values and other convenience methods.
20 ///
21 /// This is the primary trait to use when generating random values.
22 ///
23 /// # Generic usage
24 ///
25 /// The basic pattern is `fn foo<R: Rng + ?Sized>(rng: &mut R)`. Some
26 /// things are worth noting here:
27 ///
28 /// - Since `Rng: RngCore` and every `RngCore` implements `Rng`, it makes no
29 ///   difference whether we use `R: Rng` or `R: RngCore`.
30 /// - The `+ ?Sized` un-bounding allows functions to be called directly on
31 ///   type-erased references; i.e. `foo(r)` where `r: &mut RngCore`. Without
32 ///   this it would be necessary to write `foo(&mut r)`.
33 ///
34 /// An alternative pattern is possible: `fn foo<R: Rng>(rng: R)`. This has some
35 /// trade-offs. It allows the argument to be consumed directly without a `&mut`
36 /// (which is how `from_rng(thread_rng())` works); also it still works directly
37 /// on references (including type-erased references). Unfortunately within the
38 /// function `foo` it is not known whether `rng` is a reference type or not,
39 /// hence many uses of `rng` require an extra reference, either explicitly
40 /// (`distr.sample(&mut rng)`) or implicitly (`rng.gen()`); one may hope the
41 /// optimiser can remove redundant references later.
42 ///
43 /// Example:
44 ///
45 /// ```
46 /// # use rand::thread_rng;
47 /// use rand::Rng;
48 ///
49 /// fn foo<R: Rng + ?Sized>(rng: &mut R) -> f32 {
50 ///     rng.gen()
51 /// }
52 ///
53 /// # let v = foo(&mut thread_rng());
54 /// ```
55 pub trait Rng: RngCore {
56     /// Return a random value supporting the [`Standard`] distribution.
57     ///
58     /// # Example
59     ///
60     /// ```
61     /// use rand::{thread_rng, Rng};
62     ///
63     /// let mut rng = thread_rng();
64     /// let x: u32 = rng.gen();
65     /// println!("{}", x);
66     /// println!("{:?}", rng.gen::<(f64, bool)>());
67     /// ```
68     ///
69     /// # Arrays and tuples
70     ///
71     /// The `rng.gen()` method is able to generate arrays (up to 32 elements)
72     /// and tuples (up to 12 elements), so long as all element types can be
73     /// generated.
74     ///
75     /// For arrays of integers, especially for those with small element types
76     /// (< 64 bit), it will likely be faster to instead use [`Rng::fill`].
77     ///
78     /// ```
79     /// use rand::{thread_rng, Rng};
80     ///
81     /// let mut rng = thread_rng();
82     /// let tuple: (u8, i32, char) = rng.gen(); // arbitrary tuple support
83     ///
84     /// let arr1: [f32; 32] = rng.gen();        // array construction
85     /// let mut arr2 = [0u8; 128];
86     /// rng.fill(&mut arr2);                    // array fill
87     /// ```
88     ///
89     /// [`Standard`]: distributions::Standard
90     #[inline]
gen<T>(&mut self) -> T where Standard: Distribution<T>91     fn gen<T>(&mut self) -> T
92     where Standard: Distribution<T> {
93         Standard.sample(self)
94     }
95 
96     /// Generate a random value in the given range.
97     ///
98     /// This function is optimised for the case that only a single sample is
99     /// made from the given range. See also the [`Uniform`] distribution
100     /// type which may be faster if sampling from the same range repeatedly.
101     ///
102     /// Only `gen_range(low..high)` and `gen_range(low..=high)` are supported.
103     ///
104     /// # Panics
105     ///
106     /// Panics if the range is empty.
107     ///
108     /// # Example
109     ///
110     /// ```
111     /// use rand::{thread_rng, Rng};
112     ///
113     /// let mut rng = thread_rng();
114     ///
115     /// // Exclusive range
116     /// let n: u32 = rng.gen_range(0..10);
117     /// println!("{}", n);
118     /// let m: f64 = rng.gen_range(-40.0..1.3e5);
119     /// println!("{}", m);
120     ///
121     /// // Inclusive range
122     /// let n: u32 = rng.gen_range(0..=10);
123     /// println!("{}", n);
124     /// ```
125     ///
126     /// [`Uniform`]: distributions::uniform::Uniform
gen_range<T, R>(&mut self, range: R) -> T where T: SampleUniform, R: SampleRange<T>127     fn gen_range<T, R>(&mut self, range: R) -> T
128     where
129         T: SampleUniform,
130         R: SampleRange<T>
131     {
132         assert!(!range.is_empty(), "cannot sample empty range");
133         range.sample_single(self)
134     }
135 
136     /// Sample a new value, using the given distribution.
137     ///
138     /// ### Example
139     ///
140     /// ```
141     /// use rand::{thread_rng, Rng};
142     /// use rand::distributions::Uniform;
143     ///
144     /// let mut rng = thread_rng();
145     /// let x = rng.sample(Uniform::new(10u32, 15));
146     /// // Type annotation requires two types, the type and distribution; the
147     /// // distribution can be inferred.
148     /// let y = rng.sample::<u16, _>(Uniform::new(10, 15));
149     /// ```
sample<T, D: Distribution<T>>(&mut self, distr: D) -> T150     fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
151         distr.sample(self)
152     }
153 
154     /// Create an iterator that generates values using the given distribution.
155     ///
156     /// Note that this function takes its arguments by value. This works since
157     /// `(&mut R): Rng where R: Rng` and
158     /// `(&D): Distribution where D: Distribution`,
159     /// however borrowing is not automatic hence `rng.sample_iter(...)` may
160     /// need to be replaced with `(&mut rng).sample_iter(...)`.
161     ///
162     /// # Example
163     ///
164     /// ```
165     /// use rand::{thread_rng, Rng};
166     /// use rand::distributions::{Alphanumeric, Uniform, Standard};
167     ///
168     /// let mut rng = thread_rng();
169     ///
170     /// // Vec of 16 x f32:
171     /// let v: Vec<f32> = (&mut rng).sample_iter(Standard).take(16).collect();
172     ///
173     /// // String:
174     /// let s: String = (&mut rng).sample_iter(Alphanumeric)
175     ///     .take(7)
176     ///     .map(char::from)
177     ///     .collect();
178     ///
179     /// // Combined values
180     /// println!("{:?}", (&mut rng).sample_iter(Standard).take(5)
181     ///                              .collect::<Vec<(f64, bool)>>());
182     ///
183     /// // Dice-rolling:
184     /// let die_range = Uniform::new_inclusive(1, 6);
185     /// let mut roll_die = (&mut rng).sample_iter(die_range);
186     /// while roll_die.next().unwrap() != 6 {
187     ///     println!("Not a 6; rolling again!");
188     /// }
189     /// ```
sample_iter<T, D>(self, distr: D) -> distributions::DistIter<D, Self, T> where D: Distribution<T>, Self: Sized,190     fn sample_iter<T, D>(self, distr: D) -> distributions::DistIter<D, Self, T>
191     where
192         D: Distribution<T>,
193         Self: Sized,
194     {
195         distr.sample_iter(self)
196     }
197 
198     /// Fill any type implementing [`Fill`] with random data
199     ///
200     /// The distribution is expected to be uniform with portable results, but
201     /// this cannot be guaranteed for third-party implementations.
202     ///
203     /// This is identical to [`try_fill`] except that it panics on error.
204     ///
205     /// # Example
206     ///
207     /// ```
208     /// use rand::{thread_rng, Rng};
209     ///
210     /// let mut arr = [0i8; 20];
211     /// thread_rng().fill(&mut arr[..]);
212     /// ```
213     ///
214     /// [`fill_bytes`]: RngCore::fill_bytes
215     /// [`try_fill`]: Rng::try_fill
fill<T: Fill + ?Sized>(&mut self, dest: &mut T)216     fn fill<T: Fill + ?Sized>(&mut self, dest: &mut T) {
217         dest.try_fill(self).unwrap_or_else(|_| panic!("Rng::fill failed"))
218     }
219 
220     /// Fill any type implementing [`Fill`] with random data
221     ///
222     /// The distribution is expected to be uniform with portable results, but
223     /// this cannot be guaranteed for third-party implementations.
224     ///
225     /// This is identical to [`fill`] except that it forwards errors.
226     ///
227     /// # Example
228     ///
229     /// ```
230     /// # use rand::Error;
231     /// use rand::{thread_rng, Rng};
232     ///
233     /// # fn try_inner() -> Result<(), Error> {
234     /// let mut arr = [0u64; 4];
235     /// thread_rng().try_fill(&mut arr[..])?;
236     /// # Ok(())
237     /// # }
238     ///
239     /// # try_inner().unwrap()
240     /// ```
241     ///
242     /// [`try_fill_bytes`]: RngCore::try_fill_bytes
243     /// [`fill`]: Rng::fill
try_fill<T: Fill + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error>244     fn try_fill<T: Fill + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> {
245         dest.try_fill(self)
246     }
247 
248     /// Return a bool with a probability `p` of being true.
249     ///
250     /// See also the [`Bernoulli`] distribution, which may be faster if
251     /// sampling from the same probability repeatedly.
252     ///
253     /// # Example
254     ///
255     /// ```
256     /// use rand::{thread_rng, Rng};
257     ///
258     /// let mut rng = thread_rng();
259     /// println!("{}", rng.gen_bool(1.0 / 3.0));
260     /// ```
261     ///
262     /// # Panics
263     ///
264     /// If `p < 0` or `p > 1`.
265     ///
266     /// [`Bernoulli`]: distributions::Bernoulli
267     #[inline]
gen_bool(&mut self, p: f64) -> bool268     fn gen_bool(&mut self, p: f64) -> bool {
269         let d = distributions::Bernoulli::new(p).unwrap();
270         self.sample(d)
271     }
272 
273     /// Return a bool with a probability of `numerator/denominator` of being
274     /// true. I.e. `gen_ratio(2, 3)` has chance of 2 in 3, or about 67%, of
275     /// returning true. If `numerator == denominator`, then the returned value
276     /// is guaranteed to be `true`. If `numerator == 0`, then the returned
277     /// value is guaranteed to be `false`.
278     ///
279     /// See also the [`Bernoulli`] distribution, which may be faster if
280     /// sampling from the same `numerator` and `denominator` repeatedly.
281     ///
282     /// # Panics
283     ///
284     /// If `denominator == 0` or `numerator > denominator`.
285     ///
286     /// # Example
287     ///
288     /// ```
289     /// use rand::{thread_rng, Rng};
290     ///
291     /// let mut rng = thread_rng();
292     /// println!("{}", rng.gen_ratio(2, 3));
293     /// ```
294     ///
295     /// [`Bernoulli`]: distributions::Bernoulli
296     #[inline]
gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool297     fn gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool {
298         let d = distributions::Bernoulli::from_ratio(numerator, denominator).unwrap();
299         self.sample(d)
300     }
301 }
302 
303 impl<R: RngCore + ?Sized> Rng for R {}
304 
305 /// Types which may be filled with random data
306 ///
307 /// This trait allows arrays to be efficiently filled with random data.
308 ///
309 /// Implementations are expected to be portable across machines unless
310 /// clearly documented otherwise (see the
311 /// [Chapter on Portability](https://rust-random.github.io/book/portability.html)).
312 pub trait Fill {
313     /// Fill self with random data
try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>314     fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>;
315 }
316 
317 macro_rules! impl_fill_each {
318     () => {};
319     ($t:ty) => {
320         impl Fill for [$t] {
321             fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
322                 for elt in self.iter_mut() {
323                     *elt = rng.gen();
324                 }
325                 Ok(())
326             }
327         }
328     };
329     ($t:ty, $($tt:ty,)*) => {
330         impl_fill_each!($t);
331         impl_fill_each!($($tt,)*);
332     };
333 }
334 
335 impl_fill_each!(bool, char, f32, f64,);
336 
337 impl Fill for [u8] {
try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>338     fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
339         rng.try_fill_bytes(self)
340     }
341 }
342 
343 macro_rules! impl_fill {
344     () => {};
345     ($t:ty) => {
346         impl Fill for [$t] {
347             #[inline(never)] // in micro benchmarks, this improves performance
348             fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
349                 if self.len() > 0 {
350                     rng.try_fill_bytes(unsafe {
351                         slice::from_raw_parts_mut(self.as_mut_ptr()
352                             as *mut u8,
353                             self.len() * mem::size_of::<$t>()
354                         )
355                     })?;
356                     for x in self {
357                         *x = x.to_le();
358                     }
359                 }
360                 Ok(())
361             }
362         }
363 
364         impl Fill for [Wrapping<$t>] {
365             #[inline(never)]
366             fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
367                 if self.len() > 0 {
368                     rng.try_fill_bytes(unsafe {
369                         slice::from_raw_parts_mut(self.as_mut_ptr()
370                             as *mut u8,
371                             self.len() * mem::size_of::<$t>()
372                         )
373                     })?;
374                     for x in self {
375                     *x = Wrapping(x.0.to_le());
376                     }
377                 }
378                 Ok(())
379             }
380         }
381     };
382     ($t:ty, $($tt:ty,)*) => {
383         impl_fill!($t);
384         // TODO: this could replace above impl once Rust #32463 is fixed
385         // impl_fill!(Wrapping<$t>);
386         impl_fill!($($tt,)*);
387     }
388 }
389 
390 impl_fill!(u16, u32, u64, usize,);
391 #[cfg(not(target_os = "emscripten"))]
392 impl_fill!(u128);
393 impl_fill!(i8, i16, i32, i64, isize,);
394 #[cfg(not(target_os = "emscripten"))]
395 impl_fill!(i128);
396 
397 macro_rules! impl_fill_arrays {
398     ($n:expr,) => {};
399     ($n:expr, $N:ident) => {
400         impl<T> Fill for [T; $n] where [T]: Fill {
401             fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> {
402                 self[..].try_fill(rng)
403             }
404         }
405     };
406     ($n:expr, $N:ident, $($NN:ident,)*) => {
407         impl_fill_arrays!($n, $N);
408         impl_fill_arrays!($n - 1, $($NN,)*);
409     };
410     (!div $n:expr,) => {};
411     (!div $n:expr, $N:ident, $($NN:ident,)*) => {
412         impl_fill_arrays!($n, $N);
413         impl_fill_arrays!(!div $n / 2, $($NN,)*);
414     };
415 }
416 #[rustfmt::skip]
417 impl_fill_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,);
418 impl_fill_arrays!(!div 4096, N,N,N,N,N,N,N,);
419 
420 #[cfg(test)]
421 mod test {
422     use super::*;
423     use crate::test::rng;
424     use crate::rngs::mock::StepRng;
425     #[cfg(feature = "alloc")] use alloc::boxed::Box;
426 
427     #[test]
test_fill_bytes_default()428     fn test_fill_bytes_default() {
429         let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0);
430 
431         // check every remainder mod 8, both in small and big vectors.
432         let lengths = [0, 1, 2, 3, 4, 5, 6, 7, 80, 81, 82, 83, 84, 85, 86, 87];
433         for &n in lengths.iter() {
434             let mut buffer = [0u8; 87];
435             let v = &mut buffer[0..n];
436             r.fill_bytes(v);
437 
438             // use this to get nicer error messages.
439             for (i, &byte) in v.iter().enumerate() {
440                 if byte == 0 {
441                     panic!("byte {} of {} is zero", i, n)
442                 }
443             }
444         }
445     }
446 
447     #[test]
test_fill()448     fn test_fill() {
449         let x = 9041086907909331047; // a random u64
450         let mut rng = StepRng::new(x, 0);
451 
452         // Convert to byte sequence and back to u64; byte-swap twice if BE.
453         let mut array = [0u64; 2];
454         rng.fill(&mut array[..]);
455         assert_eq!(array, [x, x]);
456         assert_eq!(rng.next_u64(), x);
457 
458         // Convert to bytes then u32 in LE order
459         let mut array = [0u32; 2];
460         rng.fill(&mut array[..]);
461         assert_eq!(array, [x as u32, (x >> 32) as u32]);
462         assert_eq!(rng.next_u32(), x as u32);
463 
464         // Check equivalence using wrapped arrays
465         let mut warray = [Wrapping(0u32); 2];
466         rng.fill(&mut warray[..]);
467         assert_eq!(array[0], warray[0].0);
468         assert_eq!(array[1], warray[1].0);
469 
470         // Check equivalence for generated floats
471         let mut array = [0f32; 2];
472         rng.fill(&mut array);
473         let gen: [f32; 2] = rng.gen();
474         assert_eq!(array, gen);
475     }
476 
477     #[test]
test_fill_empty()478     fn test_fill_empty() {
479         let mut array = [0u32; 0];
480         let mut rng = StepRng::new(0, 1);
481         rng.fill(&mut array);
482         rng.fill(&mut array[..]);
483     }
484 
485     #[test]
test_gen_range_int()486     fn test_gen_range_int() {
487         let mut r = rng(101);
488         for _ in 0..1000 {
489             let a = r.gen_range(-4711..17);
490             assert!(a >= -4711 && a < 17);
491             let a = r.gen_range(-3i8..42);
492             assert!(a >= -3i8 && a < 42i8);
493             let a: u16 = r.gen_range(10..99);
494             assert!(a >= 10u16 && a < 99u16);
495             let a = r.gen_range(-100i32..2000);
496             assert!(a >= -100i32 && a < 2000i32);
497             let a: u32 = r.gen_range(12..=24);
498             assert!(a >= 12u32 && a <= 24u32);
499 
500             assert_eq!(r.gen_range(0u32..1), 0u32);
501             assert_eq!(r.gen_range(-12i64..-11), -12i64);
502             assert_eq!(r.gen_range(3_000_000..3_000_001), 3_000_000);
503         }
504     }
505 
506     #[test]
test_gen_range_float()507     fn test_gen_range_float() {
508         let mut r = rng(101);
509         for _ in 0..1000 {
510             let a = r.gen_range(-4.5..1.7);
511             assert!(a >= -4.5 && a < 1.7);
512             let a = r.gen_range(-1.1..=-0.3);
513             assert!(a >= -1.1 && a <= -0.3);
514 
515             assert_eq!(r.gen_range(0.0f32..=0.0), 0.);
516             assert_eq!(r.gen_range(-11.0..=-11.0), -11.);
517             assert_eq!(r.gen_range(3_000_000.0..=3_000_000.0), 3_000_000.);
518         }
519     }
520 
521     #[test]
522     #[should_panic]
test_gen_range_panic_int()523     fn test_gen_range_panic_int() {
524         let mut r = rng(102);
525         r.gen_range(5..-2);
526     }
527 
528     #[test]
529     #[should_panic]
test_gen_range_panic_usize()530     fn test_gen_range_panic_usize() {
531         let mut r = rng(103);
532         r.gen_range(5..2);
533     }
534 
535     #[test]
test_gen_bool()536     fn test_gen_bool() {
537         let mut r = rng(105);
538         for _ in 0..5 {
539             assert_eq!(r.gen_bool(0.0), false);
540             assert_eq!(r.gen_bool(1.0), true);
541         }
542     }
543 
544     #[test]
test_rng_trait_object()545     fn test_rng_trait_object() {
546         use crate::distributions::{Distribution, Standard};
547         let mut rng = rng(109);
548         let mut r = &mut rng as &mut dyn RngCore;
549         r.next_u32();
550         r.gen::<i32>();
551         assert_eq!(r.gen_range(0..1), 0);
552         let _c: u8 = Standard.sample(&mut r);
553     }
554 
555     #[test]
556     #[cfg(feature = "alloc")]
test_rng_boxed_trait()557     fn test_rng_boxed_trait() {
558         use crate::distributions::{Distribution, Standard};
559         let rng = rng(110);
560         let mut r = Box::new(rng) as Box<dyn RngCore>;
561         r.next_u32();
562         r.gen::<i32>();
563         assert_eq!(r.gen_range(0..1), 0);
564         let _c: u8 = Standard.sample(&mut r);
565     }
566 
567     #[test]
568     #[cfg_attr(miri, ignore)] // Miri is too slow
test_gen_ratio_average()569     fn test_gen_ratio_average() {
570         const NUM: u32 = 3;
571         const DENOM: u32 = 10;
572         const N: u32 = 100_000;
573 
574         let mut sum: u32 = 0;
575         let mut rng = rng(111);
576         for _ in 0..N {
577             if rng.gen_ratio(NUM, DENOM) {
578                 sum += 1;
579             }
580         }
581         // Have Binomial(N, NUM/DENOM) distribution
582         let expected = (NUM * N) / DENOM; // exact integer
583         assert!(((sum - expected) as i32).abs() < 500);
584     }
585 }
586