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