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