1use 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
18pub trait Rng: RngCore {
56 #[inline]
93 fn gen<T>(&mut self) -> T
94 where Standard: Distribution<T> {
95 Standard.sample(self)
96 }
97
98 fn gen_range<T, R>(&mut self, range: R) -> T
130 where
131 T: SampleUniform,
132 R: SampleRange<T>
133 {
134 if !!range.is_empty() {
::core::panicking::panic("cannot sample empty range")
};assert!(!range.is_empty(), "cannot sample empty range");
135 range.sample_single(self)
136 }
137
138 fn sample<T, D: Distribution<T>>(&mut self, distr: D) -> T {
153 distr.sample(self)
154 }
155
156 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 fn fill<T: Fill + ?Sized>(&mut self, dest: &mut T) {
219 dest.try_fill(self).unwrap_or_else(|_| ::core::panicking::panic("Rng::fill failed")panic!("Rng::fill failed"))
220 }
221
222 fn try_fill<T: Fill + ?Sized>(&mut self, dest: &mut T) -> Result<(), Error> {
247 dest.try_fill(self)
248 }
249
250 #[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 #[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
307pub trait Fill {
315 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 for [f64] {
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
for elt in self.iter_mut() { *elt = rng.gen(); }
Ok(())
}
}impl_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)] 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 impl_fill!($($tt,)*);
389 }
390}
391
392impl Fill for [u128] {
#[inline(never)]
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
if self.len() > 0 {
rng.try_fill_bytes(unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<u128>())
})?;
for x in self { *x = x.to_le(); }
}
Ok(())
}
}
impl Fill for [Wrapping<u128>] {
#[inline(never)]
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
if self.len() > 0 {
rng.try_fill_bytes(unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<u128>())
})?;
for x in self { *x = Wrapping(x.0.to_le()); }
}
Ok(())
}
}impl_fill!(u16, u32, u64, usize, u128,);
393impl Fill for [i128] {
#[inline(never)]
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
if self.len() > 0 {
rng.try_fill_bytes(unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<i128>())
})?;
for x in self { *x = x.to_le(); }
}
Ok(())
}
}
impl Fill for [Wrapping<i128>] {
#[inline(never)]
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
if self.len() > 0 {
rng.try_fill_bytes(unsafe {
slice::from_raw_parts_mut(self.as_mut_ptr() as *mut u8,
self.len() * mem::size_of::<i128>())
})?;
for x in self { *x = Wrapping(x.0.to_le()); }
}
Ok(())
}
}impl_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<T> Fill for
[T; 32 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1
- 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1 - 1]
where [T]: Fill {
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
self[..].try_fill(rng)
}
}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,);
428#[cfg(not(feature = "min_const_gen"))]
429impl<T> Fill for [T; 4096 / 2 / 2 / 2 / 2 / 2 / 2] where [T]: Fill {
fn try_fill<R: Rng + ?Sized>(&mut self, rng: &mut R)
-> Result<(), Error> {
self[..].try_fill(rng)
}
}impl_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 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 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; let mut rng = StepRng::new(x, 0);
462
463 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 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 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 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)] 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 let expected = (NUM * N) / DENOM; assert!(((sum - expected) as i32).abs() < 500);
599 }
600}