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 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 /// ``` 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 /// 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] gen<T>(&mut self) -> T where Standard: Distribution<T>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 gen_range<T, R>(&mut self, range: R) -> T where T: SampleUniform, R: SampleRange<T>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 /// ``` sample<T, D: Distribution<T>>(&mut self, distr: D) -> T152 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 /// ``` sample_iter<T, D>(self, distr: D) -> distributions::DistIter<D, Self, T> where D: Distribution<T>, Self: Sized,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 fill<T: Fill + ?Sized>(&mut self, dest: &mut T)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 try_fill<T: Fill + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error>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] gen_bool(&mut self, p: f64) -> bool270 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] gen_ratio(&mut self, numerator: u32, denominator: u32) -> bool299 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 305 impl<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)). 314 pub trait Fill { 315 /// Fill self with random data try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>316 fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>; 317 } 318 319 macro_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 337 impl_fill_each!(bool, char, f32, f64,); 338 339 impl Fill for [u8] { try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>340 fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> { 341 rng.try_fill_bytes(self) 342 } 343 } 344 345 macro_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 392 impl_fill!(u16, u32, u64, usize,); 393 #[cfg(not(target_os = "emscripten"))] 394 impl_fill!(u128); 395 impl_fill!(i8, i16, i32, i64, isize,); 396 #[cfg(not(target_os = "emscripten"))] 397 impl_fill!(i128); 398 399 #[cfg(feature = "min_const_gen")] 400 impl<T, const N: usize> Fill for [T; N] 401 where [T]: Fill 402 { try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error>403 fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> { 404 self[..].try_fill(rng) 405 } 406 } 407 408 #[cfg(not(feature = "min_const_gen"))] 409 macro_rules! impl_fill_arrays { 410 ($n:expr,) => {}; 411 ($n:expr, $N:ident) => { 412 impl<T> Fill for [T; $n] where [T]: Fill { 413 fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R) -> Result<(), Error> { 414 self[..].try_fill(rng) 415 } 416 } 417 }; 418 ($n:expr, $N:ident, $($NN:ident,)*) => { 419 impl_fill_arrays!($n, $N); 420 impl_fill_arrays!($n - 1, $($NN,)*); 421 }; 422 (!div $n:expr,) => {}; 423 (!div $n:expr, $N:ident, $($NN:ident,)*) => { 424 impl_fill_arrays!($n, $N); 425 impl_fill_arrays!(!div $n / 2, $($NN,)*); 426 }; 427 } 428 #[cfg(not(feature = "min_const_gen"))] 429 #[rustfmt::skip] 430 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,); 431 #[cfg(not(feature = "min_const_gen"))] 432 impl_fill_arrays!(!div 4096, N,N,N,N,N,N,N,); 433 434 #[cfg(test)] 435 mod test { 436 use super::*; 437 use crate::test::rng; 438 use crate::rngs::mock::StepRng; 439 #[cfg(feature = "alloc")] use alloc::boxed::Box; 440 441 #[test] test_fill_bytes_default()442 fn test_fill_bytes_default() { 443 let mut r = StepRng::new(0x11_22_33_44_55_66_77_88, 0); 444 445 // check every remainder mod 8, both in small and big vectors. 446 let lengths = [0, 1, 2, 3, 4, 5, 6, 7, 80, 81, 82, 83, 84, 85, 86, 87]; 447 for &n in lengths.iter() { 448 let mut buffer = [0u8; 87]; 449 let v = &mut buffer[0..n]; 450 r.fill_bytes(v); 451 452 // use this to get nicer error messages. 453 for (i, &byte) in v.iter().enumerate() { 454 if byte == 0 { 455 panic!("byte {} of {} is zero", i, n) 456 } 457 } 458 } 459 } 460 461 #[test] test_fill()462 fn test_fill() { 463 let x = 9041086907909331047; // a random u64 464 let mut rng = StepRng::new(x, 0); 465 466 // Convert to byte sequence and back to u64; byte-swap twice if BE. 467 let mut array = [0u64; 2]; 468 rng.fill(&mut array[..]); 469 assert_eq!(array, [x, x]); 470 assert_eq!(rng.next_u64(), x); 471 472 // Convert to bytes then u32 in LE order 473 let mut array = [0u32; 2]; 474 rng.fill(&mut array[..]); 475 assert_eq!(array, [x as u32, (x >> 32) as u32]); 476 assert_eq!(rng.next_u32(), x as u32); 477 478 // Check equivalence using wrapped arrays 479 let mut warray = [Wrapping(0u32); 2]; 480 rng.fill(&mut warray[..]); 481 assert_eq!(array[0], warray[0].0); 482 assert_eq!(array[1], warray[1].0); 483 484 // Check equivalence for generated floats 485 let mut array = [0f32; 2]; 486 rng.fill(&mut array); 487 let gen: [f32; 2] = rng.gen(); 488 assert_eq!(array, gen); 489 } 490 491 #[test] test_fill_empty()492 fn test_fill_empty() { 493 let mut array = [0u32; 0]; 494 let mut rng = StepRng::new(0, 1); 495 rng.fill(&mut array); 496 rng.fill(&mut array[..]); 497 } 498 499 #[test] test_gen_range_int()500 fn test_gen_range_int() { 501 let mut r = rng(101); 502 for _ in 0..1000 { 503 let a = r.gen_range(-4711..17); 504 assert!((-4711..17).contains(&a)); 505 let a: i8 = r.gen_range(-3..42); 506 assert!((-3..42).contains(&a)); 507 let a: u16 = r.gen_range(10..99); 508 assert!((10..99).contains(&a)); 509 let a: i32 = r.gen_range(-100..2000); 510 assert!((-100..2000).contains(&a)); 511 let a: u32 = r.gen_range(12..=24); 512 assert!((12..=24).contains(&a)); 513 514 assert_eq!(r.gen_range(0u32..1), 0u32); 515 assert_eq!(r.gen_range(-12i64..-11), -12i64); 516 assert_eq!(r.gen_range(3_000_000..3_000_001), 3_000_000); 517 } 518 } 519 520 #[test] test_gen_range_float()521 fn test_gen_range_float() { 522 let mut r = rng(101); 523 for _ in 0..1000 { 524 let a = r.gen_range(-4.5..1.7); 525 assert!((-4.5..1.7).contains(&a)); 526 let a = r.gen_range(-1.1..=-0.3); 527 assert!((-1.1..=-0.3).contains(&a)); 528 529 assert_eq!(r.gen_range(0.0f32..=0.0), 0.); 530 assert_eq!(r.gen_range(-11.0..=-11.0), -11.); 531 assert_eq!(r.gen_range(3_000_000.0..=3_000_000.0), 3_000_000.); 532 } 533 } 534 535 #[test] 536 #[should_panic] test_gen_range_panic_int()537 fn test_gen_range_panic_int() { 538 #![allow(clippy::reversed_empty_ranges)] 539 let mut r = rng(102); 540 r.gen_range(5..-2); 541 } 542 543 #[test] 544 #[should_panic] test_gen_range_panic_usize()545 fn test_gen_range_panic_usize() { 546 #![allow(clippy::reversed_empty_ranges)] 547 let mut r = rng(103); 548 r.gen_range(5..2); 549 } 550 551 #[test] test_gen_bool()552 fn test_gen_bool() { 553 #![allow(clippy::bool_assert_comparison)] 554 555 let mut r = rng(105); 556 for _ in 0..5 { 557 assert_eq!(r.gen_bool(0.0), false); 558 assert_eq!(r.gen_bool(1.0), true); 559 } 560 } 561 562 #[test] test_rng_trait_object()563 fn test_rng_trait_object() { 564 use crate::distributions::{Distribution, Standard}; 565 let mut rng = rng(109); 566 let mut r = &mut rng as &mut dyn RngCore; 567 r.next_u32(); 568 r.gen::<i32>(); 569 assert_eq!(r.gen_range(0..1), 0); 570 let _c: u8 = Standard.sample(&mut r); 571 } 572 573 #[test] 574 #[cfg(feature = "alloc")] test_rng_boxed_trait()575 fn test_rng_boxed_trait() { 576 use crate::distributions::{Distribution, Standard}; 577 let rng = rng(110); 578 let mut r = Box::new(rng) as Box<dyn RngCore>; 579 r.next_u32(); 580 r.gen::<i32>(); 581 assert_eq!(r.gen_range(0..1), 0); 582 let _c: u8 = Standard.sample(&mut r); 583 } 584 585 #[test] 586 #[cfg_attr(miri, ignore)] // Miri is too slow test_gen_ratio_average()587 fn test_gen_ratio_average() { 588 const NUM: u32 = 3; 589 const DENOM: u32 = 10; 590 const N: u32 = 100_000; 591 592 let mut sum: u32 = 0; 593 let mut rng = rng(111); 594 for _ in 0..N { 595 if rng.gen_ratio(NUM, DENOM) { 596 sum += 1; 597 } 598 } 599 // Have Binomial(N, NUM/DENOM) distribution 600 let expected = (NUM * N) / DENOM; // exact integer 601 assert!(((sum - expected) as i32).abs() < 500); 602 } 603 } 604