rand_core/lib.rs
1// Copyright 2018 Developers of the Rand project.
2// Copyright 2017-2018 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//! Random number generation traits
11//!
12//! This crate is mainly of interest to crates publishing implementations of
13//! [`RngCore`]. Other users are encouraged to use the [`rand`] crate instead
14//! which re-exports the main traits and error types.
15//!
16//! [`RngCore`] is the core trait implemented by algorithmic pseudo-random number
17//! generators and external random-number sources.
18//!
19//! [`SeedableRng`] is an extension trait for construction from fixed seeds and
20//! other random number generators.
21//!
22//! The [`le`] sub-module includes a few small functions to assist
23//! implementation of [`RngCore`] and [`SeedableRng`].
24//!
25//! [`rand`]: https://docs.rs/rand
26
27#![doc(
28 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
29 html_favicon_url = "https://www.rust-lang.org/favicon.ico",
30 html_root_url = "https://rust-random.github.io/rand/"
31)]
32#![deny(missing_docs)]
33#![deny(missing_debug_implementations)]
34#![deny(clippy::undocumented_unsafe_blocks)]
35#![doc(test(attr(allow(unused_variables), deny(warnings))))]
36#![cfg_attr(docsrs, feature(doc_cfg))]
37#![no_std]
38
39#[cfg(feature = "std")]
40extern crate std;
41
42use core::{fmt, ops::DerefMut};
43
44pub mod block;
45pub mod le;
46#[cfg(feature = "os_rng")]
47mod os;
48
49#[cfg(feature = "os_rng")]
50pub use os::{OsError, OsRng};
51
52/// Implementation-level interface for RNGs
53///
54/// This trait encapsulates the low-level functionality common to all
55/// generators, and is the "back end", to be implemented by generators.
56/// End users should normally use the [`rand::Rng`] trait
57/// which is automatically implemented for every type implementing `RngCore`.
58///
59/// Three different methods for generating random data are provided since the
60/// optimal implementation of each is dependent on the type of generator. There
61/// is no required relationship between the output of each; e.g. many
62/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64`
63/// values and drop any remaining unused bytes. The same can happen with the
64/// [`next_u32`] and [`next_u64`] methods, implementations may discard some
65/// random bits for efficiency.
66///
67/// # Properties of a generator
68///
69/// Implementers should produce bits uniformly. Pathological RNGs (e.g. constant
70/// or counting generators which rarely change some bits) may cause issues in
71/// consumers of random data, for example dead-locks in rejection samplers and
72/// obviously non-random output (e.g. a counting generator may result in
73/// apparently-constant output from a uniform-ranged distribution).
74///
75/// Algorithmic generators implementing [`SeedableRng`] should normally have
76/// *portable, reproducible* output, i.e. fix Endianness when converting values
77/// to avoid platform differences, and avoid making any changes which affect
78/// output (except by communicating that the release has breaking changes).
79///
80/// # Implementing `RngCore`
81///
82/// Typically an RNG will implement only one of the methods available
83/// in this trait directly, then use the helper functions from the
84/// [`le` module](crate::le) to implement the other methods.
85///
86/// Note that implementors of [`RngCore`] also automatically implement
87/// the [`TryRngCore`] trait with the `Error` associated type being
88/// equal to [`Infallible`].
89///
90/// It is recommended that implementations also implement:
91///
92/// - `Debug` with a custom implementation which *does not* print any internal
93/// state (at least, [`CryptoRng`]s should not risk leaking state through
94/// `Debug`).
95/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
96/// support optional at the crate level in PRNG libs.
97/// - `Clone`, if possible.
98/// - *never* implement `Copy` (accidental copies may cause repeated values).
99/// - *do not* implement `Default` for pseudorandom generators, but instead
100/// implement [`SeedableRng`], to guide users towards proper seeding.
101/// External / hardware RNGs can choose to implement `Default`.
102/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
103///
104/// [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html
105/// [`fill_bytes`]: RngCore::fill_bytes
106/// [`next_u32`]: RngCore::next_u32
107/// [`next_u64`]: RngCore::next_u64
108/// [`Infallible`]: core::convert::Infallible
109pub trait RngCore {
110 /// Return the next random `u32`.
111 fn next_u32(&mut self) -> u32;
112
113 /// Return the next random `u64`.
114 fn next_u64(&mut self) -> u64;
115
116 /// Fill `dest` with random data.
117 ///
118 /// This method should guarantee that `dest` is entirely filled
119 /// with new data, and may panic if this is impossible
120 /// (e.g. reading past the end of a file that is being used as the
121 /// source of randomness).
122 fn fill_bytes(&mut self, dst: &mut [u8]);
123}
124
125impl<T: DerefMut> RngCore for T
126where
127 T::Target: RngCore,
128{
129 #[inline]
130 fn next_u32(&mut self) -> u32 {
131 self.deref_mut().next_u32()
132 }
133
134 #[inline]
135 fn next_u64(&mut self) -> u64 {
136 self.deref_mut().next_u64()
137 }
138
139 #[inline]
140 fn fill_bytes(&mut self, dst: &mut [u8]) {
141 self.deref_mut().fill_bytes(dst);
142 }
143}
144
145/// A marker trait over [`RngCore`] for securely unpredictable RNGs
146///
147/// This marker trait indicates that the implementing generator is intended,
148/// when correctly seeded and protected from side-channel attacks such as a
149/// leaking of state, to be a cryptographically secure generator. This trait is
150/// provided as a tool to aid review of cryptographic code, but does not by
151/// itself guarantee suitability for cryptographic applications.
152///
153/// Implementors of `CryptoRng` automatically implement the [`TryCryptoRng`]
154/// trait.
155///
156/// Implementors of `CryptoRng` should only implement [`Default`] if the
157/// `default()` instances are themselves secure generators: for example if the
158/// implementing type is a stateless interface over a secure external generator
159/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
160///
161/// Formally, a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
162/// should satisfy an additional property over other generators: assuming that
163/// the generator has been appropriately seeded and has unknown state, then
164/// given the first *k* bits of an algorithm's output
165/// sequence, it should not be possible using polynomial-time algorithms to
166/// predict the next bit with probability significantly greater than 50%.
167///
168/// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
169/// state is revealed, it will not be computationally-feasible to reconstruct
170/// prior output values. This property is not required by `CryptoRng`.
171pub trait CryptoRng: RngCore {}
172
173impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
174
175/// A potentially fallible variant of [`RngCore`]
176///
177/// This trait is a generalization of [`RngCore`] to support potentially-
178/// fallible IO-based generators such as [`OsRng`].
179///
180/// All implementations of [`RngCore`] automatically support this `TryRngCore`
181/// trait, using [`Infallible`][core::convert::Infallible] as the associated
182/// `Error` type.
183///
184/// An implementation of this trait may be made compatible with code requiring
185/// an [`RngCore`] through [`TryRngCore::unwrap_err`]. The resulting RNG will
186/// panic in case the underlying fallible RNG yields an error.
187pub trait TryRngCore {
188 /// The type returned in the event of a RNG error.
189 type Error: fmt::Debug + fmt::Display;
190
191 /// Return the next random `u32`.
192 fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
193 /// Return the next random `u64`.
194 fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
195 /// Fill `dest` entirely with random data.
196 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
197
198 /// Wrap RNG with the [`UnwrapErr`] wrapper.
199 fn unwrap_err(self) -> UnwrapErr<Self>
200 where
201 Self: Sized,
202 {
203 UnwrapErr(self)
204 }
205
206 /// Wrap RNG with the [`UnwrapMut`] wrapper.
207 fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self> {
208 UnwrapMut(self)
209 }
210
211 /// Convert an [`RngCore`] to a [`RngReadAdapter`].
212 #[cfg(feature = "std")]
213 fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
214 where
215 Self: Sized,
216 {
217 RngReadAdapter { inner: self }
218 }
219}
220
221// Note that, unfortunately, this blanket impl prevents us from implementing
222// `TryRngCore` for types which can be dereferenced to `TryRngCore`, i.e. `TryRngCore`
223// will not be automatically implemented for `&mut R`, `Box<R>`, etc.
224impl<R: RngCore + ?Sized> TryRngCore for R {
225 type Error = core::convert::Infallible;
226
227 #[inline]
228 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
229 Ok(self.next_u32())
230 }
231
232 #[inline]
233 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
234 Ok(self.next_u64())
235 }
236
237 #[inline]
238 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
239 self.fill_bytes(dst);
240 Ok(())
241 }
242}
243
244/// A marker trait over [`TryRngCore`] for securely unpredictable RNGs
245///
246/// This trait is like [`CryptoRng`] but for the trait [`TryRngCore`].
247///
248/// This marker trait indicates that the implementing generator is intended,
249/// when correctly seeded and protected from side-channel attacks such as a
250/// leaking of state, to be a cryptographically secure generator. This trait is
251/// provided as a tool to aid review of cryptographic code, but does not by
252/// itself guarantee suitability for cryptographic applications.
253///
254/// Implementors of `TryCryptoRng` should only implement [`Default`] if the
255/// `default()` instances are themselves secure generators: for example if the
256/// implementing type is a stateless interface over a secure external generator
257/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
258pub trait TryCryptoRng: TryRngCore {}
259
260impl<R: CryptoRng + ?Sized> TryCryptoRng for R {}
261
262/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
263/// by panicking on potential errors.
264#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
265pub struct UnwrapErr<R: TryRngCore>(pub R);
266
267impl<R: TryRngCore> RngCore for UnwrapErr<R> {
268 #[inline]
269 fn next_u32(&mut self) -> u32 {
270 self.0.try_next_u32().unwrap()
271 }
272
273 #[inline]
274 fn next_u64(&mut self) -> u64 {
275 self.0.try_next_u64().unwrap()
276 }
277
278 #[inline]
279 fn fill_bytes(&mut self, dst: &mut [u8]) {
280 self.0.try_fill_bytes(dst).unwrap()
281 }
282}
283
284impl<R: TryCryptoRng> CryptoRng for UnwrapErr<R> {}
285
286/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
287/// by panicking on potential errors.
288#[derive(Debug, Eq, PartialEq, Hash)]
289pub struct UnwrapMut<'r, R: TryRngCore + ?Sized>(pub &'r mut R);
290
291impl<'r, R: TryRngCore + ?Sized> UnwrapMut<'r, R> {
292 /// Reborrow with a new lifetime
293 ///
294 /// Rust allows references like `&T` or `&mut T` to be "reborrowed" through
295 /// coercion: essentially, the pointer is copied under a new, shorter, lifetime.
296 /// Until rfcs#1403 lands, reborrows on user types require a method call.
297 #[inline(always)]
298 pub fn re<'b>(&'b mut self) -> UnwrapMut<'b, R>
299 where
300 'r: 'b,
301 {
302 UnwrapMut(self.0)
303 }
304}
305
306impl<R: TryRngCore + ?Sized> RngCore for UnwrapMut<'_, R> {
307 #[inline]
308 fn next_u32(&mut self) -> u32 {
309 self.0.try_next_u32().unwrap()
310 }
311
312 #[inline]
313 fn next_u64(&mut self) -> u64 {
314 self.0.try_next_u64().unwrap()
315 }
316
317 #[inline]
318 fn fill_bytes(&mut self, dst: &mut [u8]) {
319 self.0.try_fill_bytes(dst).unwrap()
320 }
321}
322
323impl<R: TryCryptoRng + ?Sized> CryptoRng for UnwrapMut<'_, R> {}
324
325/// A random number generator that can be explicitly seeded.
326///
327/// This trait encapsulates the low-level functionality common to all
328/// pseudo-random number generators (PRNGs, or algorithmic generators).
329///
330/// A generator implementing `SeedableRng` will usually be deterministic, but
331/// beware that portability and reproducibility of results **is not implied**.
332/// Refer to documentation of the generator, noting that generators named after
333/// a specific algorithm are usually tested for reproducibility against a
334/// reference vector, while `SmallRng` and `StdRng` specifically opt out of
335/// reproducibility guarantees.
336///
337/// [`rand`]: https://docs.rs/rand
338pub trait SeedableRng: Sized {
339 /// Seed type, which is restricted to types mutably-dereferenceable as `u8`
340 /// arrays (we recommend `[u8; N]` for some `N`).
341 ///
342 /// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
343 /// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
344 /// partially overlapping periods.
345 ///
346 /// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
347 ///
348 ///
349 /// # Implementing `SeedableRng` for RNGs with large seeds
350 ///
351 /// Note that [`Default`] is not implemented for large arrays `[u8; N]` with
352 /// `N` > 32. To be able to implement the traits required by `SeedableRng`
353 /// for RNGs with such large seeds, the newtype pattern can be used:
354 ///
355 /// ```
356 /// use rand_core::SeedableRng;
357 ///
358 /// const N: usize = 64;
359 /// #[derive(Clone)]
360 /// pub struct MyRngSeed(pub [u8; N]);
361 /// # #[allow(dead_code)]
362 /// pub struct MyRng(MyRngSeed);
363 ///
364 /// impl Default for MyRngSeed {
365 /// fn default() -> MyRngSeed {
366 /// MyRngSeed([0; N])
367 /// }
368 /// }
369 ///
370 /// impl AsRef<[u8]> for MyRngSeed {
371 /// fn as_ref(&self) -> &[u8] {
372 /// &self.0
373 /// }
374 /// }
375 ///
376 /// impl AsMut<[u8]> for MyRngSeed {
377 /// fn as_mut(&mut self) -> &mut [u8] {
378 /// &mut self.0
379 /// }
380 /// }
381 ///
382 /// impl SeedableRng for MyRng {
383 /// type Seed = MyRngSeed;
384 ///
385 /// fn from_seed(seed: MyRngSeed) -> MyRng {
386 /// MyRng(seed)
387 /// }
388 /// }
389 /// ```
390 type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]>;
391
392 /// Create a new PRNG using the given seed.
393 ///
394 /// PRNG implementations are allowed to assume that bits in the seed are
395 /// well distributed. That means usually that the number of one and zero
396 /// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
397 /// Note that many non-cryptographic PRNGs will show poor quality output
398 /// if this is not adhered to. If you wish to seed from simple numbers, use
399 /// `seed_from_u64` instead.
400 ///
401 /// All PRNG implementations should be reproducible unless otherwise noted:
402 /// given a fixed `seed`, the same sequence of output should be produced
403 /// on all runs, library versions and architectures (e.g. check endianness).
404 /// Any "value-breaking" changes to the generator should require bumping at
405 /// least the minor version and documentation of the change.
406 ///
407 /// It is not required that this function yield the same state as a
408 /// reference implementation of the PRNG given equivalent seed; if necessary
409 /// another constructor replicating behaviour from a reference
410 /// implementation can be added.
411 ///
412 /// PRNG implementations should make sure `from_seed` never panics. In the
413 /// case that some special values (like an all zero seed) are not viable
414 /// seeds it is preferable to map these to alternative constant value(s),
415 /// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
416 /// seed"). This is assuming only a small number of values must be rejected.
417 fn from_seed(seed: Self::Seed) -> Self;
418
419 /// Create a new PRNG using a `u64` seed.
420 ///
421 /// This is a convenience-wrapper around `from_seed` to allow construction
422 /// of any `SeedableRng` from a simple `u64` value. It is designed such that
423 /// low Hamming Weight numbers like 0 and 1 can be used and should still
424 /// result in good, independent seeds to the PRNG which is returned.
425 ///
426 /// This **is not suitable for cryptography**, as should be clear given that
427 /// the input size is only 64 bits.
428 ///
429 /// Implementations for PRNGs *may* provide their own implementations of
430 /// this function, but the default implementation should be good enough for
431 /// all purposes. *Changing* the implementation of this function should be
432 /// considered a value-breaking change.
433 fn seed_from_u64(mut state: u64) -> Self {
434 // We use PCG32 to generate a u32 sequence, and copy to the seed
435 fn pcg32(state: &mut u64) -> [u8; 4] {
436 const MUL: u64 = 6364136223846793005;
437 const INC: u64 = 11634580027462260723;
438
439 // We advance the state first (to get away from the input value,
440 // in case it has low Hamming Weight).
441 *state = state.wrapping_mul(MUL).wrapping_add(INC);
442 let state = *state;
443
444 // Use PCG output function with to_le to generate x:
445 let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
446 let rot = (state >> 59) as u32;
447 let x = xorshifted.rotate_right(rot);
448 x.to_le_bytes()
449 }
450
451 let mut seed = Self::Seed::default();
452 let mut iter = seed.as_mut().chunks_exact_mut(4);
453 for chunk in &mut iter {
454 chunk.copy_from_slice(&pcg32(&mut state));
455 }
456 let rem = iter.into_remainder();
457 if !rem.is_empty() {
458 rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
459 }
460
461 Self::from_seed(seed)
462 }
463
464 /// Create a new PRNG seeded from an infallible `Rng`.
465 ///
466 /// This may be useful when needing to rapidly seed many PRNGs from a master
467 /// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
468 ///
469 /// The master PRNG should be at least as high quality as the child PRNGs.
470 /// When seeding non-cryptographic child PRNGs, we recommend using a
471 /// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
472 /// correlations between the child PRNGs. If this is not possible (e.g.
473 /// forking using small non-crypto PRNGs) ensure that your PRNG has a good
474 /// mixing function on the output or consider use of a hash function with
475 /// `from_seed`.
476 ///
477 /// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
478 /// extreme example of what can go wrong: the new PRNG will be a clone
479 /// of the parent.
480 ///
481 /// PRNG implementations are allowed to assume that a good RNG is provided
482 /// for seeding, and that it is cryptographically secure when appropriate.
483 /// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
484 /// method should ensure the implementation satisfies reproducibility
485 /// (in prior versions this was not required).
486 ///
487 /// [`rand`]: https://docs.rs/rand
488 fn from_rng<R: RngCore + ?Sized>(rng: &mut R) -> Self {
489 let mut seed = Self::Seed::default();
490 rng.fill_bytes(seed.as_mut());
491 Self::from_seed(seed)
492 }
493
494 /// Create a new PRNG seeded from a potentially fallible `Rng`.
495 ///
496 /// See [`from_rng`][SeedableRng::from_rng] docs for more information.
497 fn try_from_rng<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
498 let mut seed = Self::Seed::default();
499 rng.try_fill_bytes(seed.as_mut())?;
500 Ok(Self::from_seed(seed))
501 }
502
503 /// Creates a new instance of the RNG seeded via [`getrandom`].
504 ///
505 /// This method is the recommended way to construct non-deterministic PRNGs
506 /// since it is convenient and secure.
507 ///
508 /// Note that this method may panic on (extremely unlikely) [`getrandom`] errors.
509 /// If it's not desirable, use the [`try_from_os_rng`] method instead.
510 ///
511 /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
512 /// issue, one may prefer to seed from a local PRNG, e.g.
513 /// `from_rng(rand::rng()).unwrap()`.
514 ///
515 /// # Panics
516 ///
517 /// If [`getrandom`] is unable to provide secure entropy this method will panic.
518 ///
519 /// [`getrandom`]: https://docs.rs/getrandom
520 /// [`try_from_os_rng`]: SeedableRng::try_from_os_rng
521 #[cfg(feature = "os_rng")]
522 fn from_os_rng() -> Self {
523 match Self::try_from_os_rng() {
524 Ok(res) => res,
525 Err(err) => panic!("from_os_rng failed: {}", err),
526 }
527 }
528
529 /// Creates a new instance of the RNG seeded via [`getrandom`] without unwrapping
530 /// potential [`getrandom`] errors.
531 ///
532 /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
533 /// issue, one may prefer to seed from a local PRNG, e.g.
534 /// `from_rng(&mut rand::rng()).unwrap()`.
535 ///
536 /// [`getrandom`]: https://docs.rs/getrandom
537 #[cfg(feature = "os_rng")]
538 fn try_from_os_rng() -> Result<Self, getrandom::Error> {
539 let mut seed = Self::Seed::default();
540 getrandom::fill(seed.as_mut())?;
541 let res = Self::from_seed(seed);
542 Ok(res)
543 }
544}
545
546/// Adapter that enables reading through a [`io::Read`](std::io::Read) from a [`RngCore`].
547///
548/// # Examples
549///
550/// ```no_run
551/// # use std::{io, io::Read};
552/// # use std::fs::File;
553/// # use rand_core::{OsRng, TryRngCore};
554///
555/// io::copy(&mut OsRng.read_adapter().take(100), &mut File::create("/tmp/random.bytes").unwrap()).unwrap();
556/// ```
557#[cfg(feature = "std")]
558pub struct RngReadAdapter<'a, R: TryRngCore + ?Sized> {
559 inner: &'a mut R,
560}
561
562#[cfg(feature = "std")]
563impl<R: TryRngCore + ?Sized> std::io::Read for RngReadAdapter<'_, R> {
564 #[inline]
565 fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
566 self.inner
567 .try_fill_bytes(buf)
568 .map_err(|err| std::io::Error::other(std::format!("RNG error: {err}")))?;
569 Ok(buf.len())
570 }
571}
572
573#[cfg(feature = "std")]
574impl<R: TryRngCore + ?Sized> std::fmt::Debug for RngReadAdapter<'_, R> {
575 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
576 f.debug_struct("ReadAdapter").finish()
577 }
578}
579
580#[cfg(test)]
581mod test {
582 use super::*;
583
584 #[test]
585 fn test_seed_from_u64() {
586 struct SeedableNum(u64);
587 impl SeedableRng for SeedableNum {
588 type Seed = [u8; 8];
589
590 fn from_seed(seed: Self::Seed) -> Self {
591 let mut x = [0u64; 1];
592 le::read_u64_into(&seed, &mut x);
593 SeedableNum(x[0])
594 }
595 }
596
597 const N: usize = 8;
598 const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
599 let mut results = [0u64; N];
600 for (i, seed) in SEEDS.iter().enumerate() {
601 let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
602 results[i] = x;
603 }
604
605 for (i1, r1) in results.iter().enumerate() {
606 let weight = r1.count_ones();
607 // This is the binomial distribution B(64, 0.5), so chance of
608 // weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
609 // weight > 44.
610 assert!((20..=44).contains(&weight));
611
612 for (i2, r2) in results.iter().enumerate() {
613 if i1 == i2 {
614 continue;
615 }
616 let diff_weight = (r1 ^ r2).count_ones();
617 assert!(diff_weight >= 20);
618 }
619 }
620
621 // value-breakage test:
622 assert_eq!(results[0], 5029875928683246316);
623 }
624
625 // A stub RNG.
626 struct SomeRng;
627
628 impl RngCore for SomeRng {
629 fn next_u32(&mut self) -> u32 {
630 unimplemented!()
631 }
632 fn next_u64(&mut self) -> u64 {
633 unimplemented!()
634 }
635 fn fill_bytes(&mut self, _: &mut [u8]) {
636 unimplemented!()
637 }
638 }
639
640 impl CryptoRng for SomeRng {}
641
642 #[test]
643 fn dyn_rngcore_to_tryrngcore() {
644 // Illustrates the need for `+ ?Sized` bound in `impl<R: RngCore> TryRngCore for R`.
645
646 // A method in another crate taking a fallible RNG
647 fn third_party_api(_rng: &mut (impl TryRngCore + ?Sized)) -> bool {
648 true
649 }
650
651 // A method in our crate requiring an infallible RNG
652 fn my_api(rng: &mut dyn RngCore) -> bool {
653 // We want to call the method above
654 third_party_api(rng)
655 }
656
657 assert!(my_api(&mut SomeRng));
658 }
659
660 #[test]
661 fn dyn_cryptorng_to_trycryptorng() {
662 // Illustrates the need for `+ ?Sized` bound in `impl<R: CryptoRng> TryCryptoRng for R`.
663
664 // A method in another crate taking a fallible RNG
665 fn third_party_api(_rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
666 true
667 }
668
669 // A method in our crate requiring an infallible RNG
670 fn my_api(rng: &mut dyn CryptoRng) -> bool {
671 // We want to call the method above
672 third_party_api(rng)
673 }
674
675 assert!(my_api(&mut SomeRng));
676 }
677
678 #[test]
679 fn dyn_unwrap_mut_tryrngcore() {
680 // Illustrates the need for `+ ?Sized` bound in
681 // `impl<R: TryRngCore> RngCore for UnwrapMut<'_, R>`.
682
683 fn third_party_api(_rng: &mut impl RngCore) -> bool {
684 true
685 }
686
687 fn my_api(rng: &mut (impl TryRngCore + ?Sized)) -> bool {
688 let mut infallible_rng = rng.unwrap_mut();
689 third_party_api(&mut infallible_rng)
690 }
691
692 assert!(my_api(&mut SomeRng));
693 }
694
695 #[test]
696 fn dyn_unwrap_mut_trycryptorng() {
697 // Illustrates the need for `+ ?Sized` bound in
698 // `impl<R: TryCryptoRng> CryptoRng for UnwrapMut<'_, R>`.
699
700 fn third_party_api(_rng: &mut impl CryptoRng) -> bool {
701 true
702 }
703
704 fn my_api(rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
705 let mut infallible_rng = rng.unwrap_mut();
706 third_party_api(&mut infallible_rng)
707 }
708
709 assert!(my_api(&mut SomeRng));
710 }
711
712 #[test]
713 fn reborrow_unwrap_mut() {
714 struct FourRng;
715
716 impl TryRngCore for FourRng {
717 type Error = core::convert::Infallible;
718 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
719 Ok(4)
720 }
721 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
722 unimplemented!()
723 }
724 fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> {
725 unimplemented!()
726 }
727 }
728
729 let mut rng = FourRng;
730 let mut rng = rng.unwrap_mut();
731
732 assert_eq!(rng.next_u32(), 4);
733 {
734 let mut rng2 = rng.re();
735 assert_eq!(rng2.next_u32(), 4);
736 // Make sure rng2 is dropped.
737 }
738 assert_eq!(rng.next_u32(), 4);
739 }
740}