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#![doc(test(attr(allow(unused_variables), deny(warnings))))]
35#![cfg_attr(docsrs, feature(doc_auto_cfg))]
36#![no_std]
37
38#[cfg(feature = "std")]
39extern crate std;
40
41use core::{fmt, ops::DerefMut};
42
43pub mod block;
44pub mod impls;
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/// Implementers should produce bits uniformly. Pathological RNGs (e.g. always
68/// returning the same value, or never setting certain bits) can break rejection
69/// sampling used by random distributions, and also break other RNGs when
70/// seeding them via [`SeedableRng::from_rng`].
71///
72/// Algorithmic generators implementing [`SeedableRng`] should normally have
73/// *portable, reproducible* output, i.e. fix Endianness when converting values
74/// to avoid platform differences, and avoid making any changes which affect
75/// output (except by communicating that the release has breaking changes).
76///
77/// Typically an RNG will implement only one of the methods available
78/// in this trait directly, then use the helper functions from the
79/// [`impls`] module to implement the other methods.
80///
81/// Note that implementors of [`RngCore`] also automatically implement
82/// the [`TryRngCore`] trait with the `Error` associated type being
83/// equal to [`Infallible`].
84///
85/// It is recommended that implementations also implement:
86///
87/// - `Debug` with a custom implementation which *does not* print any internal
88///   state (at least, [`CryptoRng`]s should not risk leaking state through
89///   `Debug`).
90/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
91///   support optional at the crate level in PRNG libs.
92/// - `Clone`, if possible.
93/// - *never* implement `Copy` (accidental copies may cause repeated values).
94/// - *do not* implement `Default` for pseudorandom generators, but instead
95///   implement [`SeedableRng`], to guide users towards proper seeding.
96///   External / hardware RNGs can choose to implement `Default`.
97/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
98///
99/// # Example
100///
101/// A simple example, obviously not generating very *random* output:
102///
103/// ```
104/// #![allow(dead_code)]
105/// use rand_core::{RngCore, impls};
106///
107/// struct CountingRng(u64);
108///
109/// impl RngCore for CountingRng {
110///     fn next_u32(&mut self) -> u32 {
111///         self.next_u64() as u32
112///     }
113///
114///     fn next_u64(&mut self) -> u64 {
115///         self.0 += 1;
116///         self.0
117///     }
118///
119///     fn fill_bytes(&mut self, dst: &mut [u8]) {
120///         impls::fill_bytes_via_next(self, dst)
121///     }
122/// }
123/// ```
124///
125/// [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html
126/// [`fill_bytes`]: RngCore::fill_bytes
127/// [`next_u32`]: RngCore::next_u32
128/// [`next_u64`]: RngCore::next_u64
129/// [`Infallible`]: core::convert::Infallible
130pub trait RngCore {
131    /// Return the next random `u32`.
132    ///
133    /// RNGs must implement at least one method from this trait directly. In
134    /// the case this method is not implemented directly, it can be implemented
135    /// using `self.next_u64() as u32` or via [`impls::next_u32_via_fill`].
136    fn next_u32(&mut self) -> u32;
137
138    /// Return the next random `u64`.
139    ///
140    /// RNGs must implement at least one method from this trait directly. In
141    /// the case this method is not implemented directly, it can be implemented
142    /// via [`impls::next_u64_via_u32`] or via [`impls::next_u64_via_fill`].
143    fn next_u64(&mut self) -> u64;
144
145    /// Fill `dest` with random data.
146    ///
147    /// RNGs must implement at least one method from this trait directly. In
148    /// the case this method is not implemented directly, it can be implemented
149    /// via [`impls::fill_bytes_via_next`].
150    ///
151    /// This method should guarantee that `dest` is entirely filled
152    /// with new data, and may panic if this is impossible
153    /// (e.g. reading past the end of a file that is being used as the
154    /// source of randomness).
155    fn fill_bytes(&mut self, dst: &mut [u8]);
156}
157
158impl<T: DerefMut> RngCore for T
159where
160    T::Target: RngCore,
161{
162    #[inline]
163    fn next_u32(&mut self) -> u32 {
164        self.deref_mut().next_u32()
165    }
166
167    #[inline]
168    fn next_u64(&mut self) -> u64 {
169        self.deref_mut().next_u64()
170    }
171
172    #[inline]
173    fn fill_bytes(&mut self, dst: &mut [u8]) {
174        self.deref_mut().fill_bytes(dst);
175    }
176}
177
178/// A marker trait used to indicate that an [`RngCore`] implementation is
179/// supposed to be cryptographically secure.
180///
181/// *Cryptographically secure generators*, also known as *CSPRNGs*, should
182/// satisfy an additional properties over other generators: given the first
183/// *k* bits of an algorithm's output
184/// sequence, it should not be possible using polynomial-time algorithms to
185/// predict the next bit with probability significantly greater than 50%.
186///
187/// Some generators may satisfy an additional property, however this is not
188/// required by this trait: if the CSPRNG's state is revealed, it should not be
189/// computationally-feasible to reconstruct output prior to this. Some other
190/// generators allow backwards-computation and are considered *reversible*.
191///
192/// Note that this trait is provided for guidance only and cannot guarantee
193/// suitability for cryptographic applications. In general it should only be
194/// implemented for well-reviewed code implementing well-regarded algorithms.
195///
196/// Note also that use of a `CryptoRng` does not protect against other
197/// weaknesses such as seeding from a weak entropy source or leaking state.
198///
199/// Note that implementors of [`CryptoRng`] also automatically implement
200/// the [`TryCryptoRng`] trait.
201///
202/// [`BlockRngCore`]: block::BlockRngCore
203/// [`Infallible`]: core::convert::Infallible
204pub trait CryptoRng: RngCore {}
205
206impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
207
208/// A potentially fallible variant of [`RngCore`]
209///
210/// This trait is a generalization of [`RngCore`] to support potentially-
211/// fallible IO-based generators such as [`OsRng`].
212///
213/// All implementations of [`RngCore`] automatically support this `TryRngCore`
214/// trait, using [`Infallible`][core::convert::Infallible] as the associated
215/// `Error` type.
216///
217/// An implementation of this trait may be made compatible with code requiring
218/// an [`RngCore`] through [`TryRngCore::unwrap_err`]. The resulting RNG will
219/// panic in case the underlying fallible RNG yields an error.
220pub trait TryRngCore {
221    /// The type returned in the event of a RNG error.
222    type Error: fmt::Debug + fmt::Display;
223
224    /// Return the next random `u32`.
225    fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
226    /// Return the next random `u64`.
227    fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
228    /// Fill `dest` entirely with random data.
229    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
230
231    /// Wrap RNG with the [`UnwrapErr`] wrapper.
232    fn unwrap_err(self) -> UnwrapErr<Self>
233    where
234        Self: Sized,
235    {
236        UnwrapErr(self)
237    }
238
239    /// Convert an [`RngCore`] to a [`RngReadAdapter`].
240    #[cfg(feature = "std")]
241    fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
242    where
243        Self: Sized,
244    {
245        RngReadAdapter { inner: self }
246    }
247}
248
249// Note that, unfortunately, this blanket impl prevents us from implementing
250// `TryRngCore` for types which can be dereferenced to `TryRngCore`, i.e. `TryRngCore`
251// will not be automatically implemented for `&mut R`, `Box<R>`, etc.
252impl<R: RngCore> TryRngCore for R {
253    type Error = core::convert::Infallible;
254
255    #[inline]
256    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
257        Ok(self.next_u32())
258    }
259
260    #[inline]
261    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
262        Ok(self.next_u64())
263    }
264
265    #[inline]
266    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
267        self.fill_bytes(dst);
268        Ok(())
269    }
270}
271
272/// A marker trait used to indicate that a [`TryRngCore`] implementation is
273/// supposed to be cryptographically secure.
274///
275/// See [`CryptoRng`] docs for more information about cryptographically secure generators.
276pub trait TryCryptoRng: TryRngCore {}
277
278impl<R: CryptoRng> TryCryptoRng for R {}
279
280/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
281/// by panicking on potential errors.
282#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
283pub struct UnwrapErr<R: TryRngCore>(pub R);
284
285impl<R: TryRngCore> RngCore for UnwrapErr<R> {
286    #[inline]
287    fn next_u32(&mut self) -> u32 {
288        self.0.try_next_u32().unwrap()
289    }
290
291    #[inline]
292    fn next_u64(&mut self) -> u64 {
293        self.0.try_next_u64().unwrap()
294    }
295
296    #[inline]
297    fn fill_bytes(&mut self, dst: &mut [u8]) {
298        self.0.try_fill_bytes(dst).unwrap()
299    }
300}
301
302impl<R: TryCryptoRng> CryptoRng for UnwrapErr<R> {}
303
304/// A random number generator that can be explicitly seeded.
305///
306/// This trait encapsulates the low-level functionality common to all
307/// pseudo-random number generators (PRNGs, or algorithmic generators).
308///
309/// [`rand`]: https://docs.rs/rand
310pub trait SeedableRng: Sized {
311    /// Seed type, which is restricted to types mutably-dereferenceable as `u8`
312    /// arrays (we recommend `[u8; N]` for some `N`).
313    ///
314    /// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
315    /// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
316    /// partially overlapping periods.
317    ///
318    /// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
319    ///
320    ///
321    /// # Implementing `SeedableRng` for RNGs with large seeds
322    ///
323    /// Note that [`Default`] is not implemented for large arrays `[u8; N]` with
324    /// `N` > 32. To be able to implement the traits required by `SeedableRng`
325    /// for RNGs with such large seeds, the newtype pattern can be used:
326    ///
327    /// ```
328    /// use rand_core::SeedableRng;
329    ///
330    /// const N: usize = 64;
331    /// #[derive(Clone)]
332    /// pub struct MyRngSeed(pub [u8; N]);
333    /// # #[allow(dead_code)]
334    /// pub struct MyRng(MyRngSeed);
335    ///
336    /// impl Default for MyRngSeed {
337    ///     fn default() -> MyRngSeed {
338    ///         MyRngSeed([0; N])
339    ///     }
340    /// }
341    ///
342    /// impl AsRef<[u8]> for MyRngSeed {
343    ///     fn as_ref(&self) -> &[u8] {
344    ///         &self.0
345    ///     }
346    /// }
347    ///
348    /// impl AsMut<[u8]> for MyRngSeed {
349    ///     fn as_mut(&mut self) -> &mut [u8] {
350    ///         &mut self.0
351    ///     }
352    /// }
353    ///
354    /// impl SeedableRng for MyRng {
355    ///     type Seed = MyRngSeed;
356    ///
357    ///     fn from_seed(seed: MyRngSeed) -> MyRng {
358    ///         MyRng(seed)
359    ///     }
360    /// }
361    /// ```
362    type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]>;
363
364    /// Create a new PRNG using the given seed.
365    ///
366    /// PRNG implementations are allowed to assume that bits in the seed are
367    /// well distributed. That means usually that the number of one and zero
368    /// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
369    /// Note that many non-cryptographic PRNGs will show poor quality output
370    /// if this is not adhered to. If you wish to seed from simple numbers, use
371    /// `seed_from_u64` instead.
372    ///
373    /// All PRNG implementations should be reproducible unless otherwise noted:
374    /// given a fixed `seed`, the same sequence of output should be produced
375    /// on all runs, library versions and architectures (e.g. check endianness).
376    /// Any "value-breaking" changes to the generator should require bumping at
377    /// least the minor version and documentation of the change.
378    ///
379    /// It is not required that this function yield the same state as a
380    /// reference implementation of the PRNG given equivalent seed; if necessary
381    /// another constructor replicating behaviour from a reference
382    /// implementation can be added.
383    ///
384    /// PRNG implementations should make sure `from_seed` never panics. In the
385    /// case that some special values (like an all zero seed) are not viable
386    /// seeds it is preferable to map these to alternative constant value(s),
387    /// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
388    /// seed"). This is assuming only a small number of values must be rejected.
389    fn from_seed(seed: Self::Seed) -> Self;
390
391    /// Create a new PRNG using a `u64` seed.
392    ///
393    /// This is a convenience-wrapper around `from_seed` to allow construction
394    /// of any `SeedableRng` from a simple `u64` value. It is designed such that
395    /// low Hamming Weight numbers like 0 and 1 can be used and should still
396    /// result in good, independent seeds to the PRNG which is returned.
397    ///
398    /// This **is not suitable for cryptography**, as should be clear given that
399    /// the input size is only 64 bits.
400    ///
401    /// Implementations for PRNGs *may* provide their own implementations of
402    /// this function, but the default implementation should be good enough for
403    /// all purposes. *Changing* the implementation of this function should be
404    /// considered a value-breaking change.
405    fn seed_from_u64(mut state: u64) -> Self {
406        // We use PCG32 to generate a u32 sequence, and copy to the seed
407        fn pcg32(state: &mut u64) -> [u8; 4] {
408            const MUL: u64 = 6364136223846793005;
409            const INC: u64 = 11634580027462260723;
410
411            // We advance the state first (to get away from the input value,
412            // in case it has low Hamming Weight).
413            *state = state.wrapping_mul(MUL).wrapping_add(INC);
414            let state = *state;
415
416            // Use PCG output function with to_le to generate x:
417            let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
418            let rot = (state >> 59) as u32;
419            let x = xorshifted.rotate_right(rot);
420            x.to_le_bytes()
421        }
422
423        let mut seed = Self::Seed::default();
424        let mut iter = seed.as_mut().chunks_exact_mut(4);
425        for chunk in &mut iter {
426            chunk.copy_from_slice(&pcg32(&mut state));
427        }
428        let rem = iter.into_remainder();
429        if !rem.is_empty() {
430            rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
431        }
432
433        Self::from_seed(seed)
434    }
435
436    /// Create a new PRNG seeded from an infallible `Rng`.
437    ///
438    /// This may be useful when needing to rapidly seed many PRNGs from a master
439    /// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
440    ///
441    /// The master PRNG should be at least as high quality as the child PRNGs.
442    /// When seeding non-cryptographic child PRNGs, we recommend using a
443    /// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
444    /// correlations between the child PRNGs. If this is not possible (e.g.
445    /// forking using small non-crypto PRNGs) ensure that your PRNG has a good
446    /// mixing function on the output or consider use of a hash function with
447    /// `from_seed`.
448    ///
449    /// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
450    /// extreme example of what can go wrong: the new PRNG will be a clone
451    /// of the parent.
452    ///
453    /// PRNG implementations are allowed to assume that a good RNG is provided
454    /// for seeding, and that it is cryptographically secure when appropriate.
455    /// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
456    /// method should ensure the implementation satisfies reproducibility
457    /// (in prior versions this was not required).
458    ///
459    /// [`rand`]: https://docs.rs/rand
460    fn from_rng(rng: &mut impl RngCore) -> Self {
461        let mut seed = Self::Seed::default();
462        rng.fill_bytes(seed.as_mut());
463        Self::from_seed(seed)
464    }
465
466    /// Create a new PRNG seeded from a potentially fallible `Rng`.
467    ///
468    /// See [`from_rng`][SeedableRng::from_rng] docs for more information.
469    fn try_from_rng<R: TryRngCore>(rng: &mut R) -> Result<Self, R::Error> {
470        let mut seed = Self::Seed::default();
471        rng.try_fill_bytes(seed.as_mut())?;
472        Ok(Self::from_seed(seed))
473    }
474
475    /// Creates a new instance of the RNG seeded via [`getrandom`].
476    ///
477    /// This method is the recommended way to construct non-deterministic PRNGs
478    /// since it is convenient and secure.
479    ///
480    /// Note that this method may panic on (extremely unlikely) [`getrandom`] errors.
481    /// If it's not desirable, use the [`try_from_os_rng`] method instead.
482    ///
483    /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
484    /// issue, one may prefer to seed from a local PRNG, e.g.
485    /// `from_rng(rand::rng()).unwrap()`.
486    ///
487    /// # Panics
488    ///
489    /// If [`getrandom`] is unable to provide secure entropy this method will panic.
490    ///
491    /// [`getrandom`]: https://docs.rs/getrandom
492    /// [`try_from_os_rng`]: SeedableRng::try_from_os_rng
493    #[cfg(feature = "os_rng")]
494    fn from_os_rng() -> Self {
495        match Self::try_from_os_rng() {
496            Ok(res) => res,
497            Err(err) => panic!("from_os_rng failed: {}", err),
498        }
499    }
500
501    /// Creates a new instance of the RNG seeded via [`getrandom`] without unwrapping
502    /// potential [`getrandom`] errors.
503    ///
504    /// In case the overhead of using [`getrandom`] to seed *many* PRNGs is an
505    /// issue, one may prefer to seed from a local PRNG, e.g.
506    /// `from_rng(&mut rand::rng()).unwrap()`.
507    ///
508    /// [`getrandom`]: https://docs.rs/getrandom
509    #[cfg(feature = "os_rng")]
510    fn try_from_os_rng() -> Result<Self, getrandom::Error> {
511        let mut seed = Self::Seed::default();
512        getrandom::fill(seed.as_mut())?;
513        let res = Self::from_seed(seed);
514        Ok(res)
515    }
516}
517
518/// Adapter that enables reading through a [`io::Read`](std::io::Read) from a [`RngCore`].
519///
520/// # Examples
521///
522/// ```no_run
523/// # use std::{io, io::Read};
524/// # use std::fs::File;
525/// # use rand_core::{OsRng, TryRngCore};
526///
527/// io::copy(&mut OsRng.read_adapter().take(100), &mut File::create("/tmp/random.bytes").unwrap()).unwrap();
528/// ```
529#[cfg(feature = "std")]
530pub struct RngReadAdapter<'a, R: TryRngCore + ?Sized> {
531    inner: &'a mut R,
532}
533
534#[cfg(feature = "std")]
535impl<R: TryRngCore + ?Sized> std::io::Read for RngReadAdapter<'_, R> {
536    #[inline]
537    fn read(&mut self, buf: &mut [u8]) -> Result<usize, std::io::Error> {
538        self.inner.try_fill_bytes(buf).map_err(|err| {
539            std::io::Error::new(std::io::ErrorKind::Other, std::format!("RNG error: {err}"))
540        })?;
541        Ok(buf.len())
542    }
543}
544
545#[cfg(feature = "std")]
546impl<R: TryRngCore + ?Sized> std::fmt::Debug for RngReadAdapter<'_, R> {
547    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
548        f.debug_struct("ReadAdapter").finish()
549    }
550}
551
552#[cfg(test)]
553mod test {
554    use super::*;
555
556    #[test]
557    fn test_seed_from_u64() {
558        struct SeedableNum(u64);
559        impl SeedableRng for SeedableNum {
560            type Seed = [u8; 8];
561
562            fn from_seed(seed: Self::Seed) -> Self {
563                let mut x = [0u64; 1];
564                le::read_u64_into(&seed, &mut x);
565                SeedableNum(x[0])
566            }
567        }
568
569        const N: usize = 8;
570        const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
571        let mut results = [0u64; N];
572        for (i, seed) in SEEDS.iter().enumerate() {
573            let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
574            results[i] = x;
575        }
576
577        for (i1, r1) in results.iter().enumerate() {
578            let weight = r1.count_ones();
579            // This is the binomial distribution B(64, 0.5), so chance of
580            // weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
581            // weight > 44.
582            assert!((20..=44).contains(&weight));
583
584            for (i2, r2) in results.iter().enumerate() {
585                if i1 == i2 {
586                    continue;
587                }
588                let diff_weight = (r1 ^ r2).count_ones();
589                assert!(diff_weight >= 20);
590            }
591        }
592
593        // value-breakage test:
594        assert_eq!(results[0], 5029875928683246316);
595    }
596}