Debian Codegraph @

debian/rust-vendor/rand_core/src/lib.rs

raw
1 // Hide badges from generated docs
2 //! <style> .badges { display: none; } </style>
3
4 #![no_std]
5 #![doc = include_str!("../README.md")]
6 #![doc(
7 html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
8 html_favicon_url = "https://www.rust-lang.org/favicon.ico"
9 )]
10
11 use core::ops::DerefMut;
12
13 pub use core::convert::Infallible;
14
15 pub mod block;
16 pub mod utils;
17
18 mod seedable_rng;
19 mod unwrap_err;
20 mod word;
21
22 pub use seedable_rng::SeedableRng;
23 pub use unwrap_err::UnwrapErr;
24
25 /// Trait for infallible random number generators
26 ///
27 /// `Rng` is a sub-trait of [`TryRng`] for infallible generators.
28 ///
29 /// # Requirements
30 ///
31 /// See [`TryRng`#Requirements] which also apply here.
32 ///
33 /// # Usage
34 ///
35 /// The [`rand`] crate provides higher level functionality, for example
36 /// generation of floating-point values, uniform ranged sampling and shuffling
37 /// sequences. In particular, [`rand::RngExt`] is an extension trait over `Rng`
38 /// providing many of the methods one might expect to be able to use on an RNG.
39 ///
40 /// # Implementing `Rng`
41 ///
42 /// Implement [`TryRng`] with <code>type Error = [core::convert::Infallible][]</code>.
43 ///
44 /// [`rand`]: https://docs.rs/rand/
45 /// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
46 /// [`fill_bytes`]: Rng::fill_bytes
47 /// [`next_u32`]: Rng::next_u32
48 /// [`next_u64`]: Rng::next_u64
49 pub trait Rng: TryRng<Error = Infallible> {
50 /// Return the next random `u32`.
51 fn next_u32(&mut self) -> u32;
52
53 /// Return the next random `u64`.
54 fn next_u64(&mut self) -> u64;
55
56 /// Fill `dest` with random data.
57 ///
58 /// This method should guarantee that `dest` is entirely filled
59 /// with new data, and may panic if this is impossible
60 /// (e.g. reading past the end of a file that is being used as the
61 /// source of randomness).
62 fn fill_bytes(&mut self, dst: &mut [u8]);
63 }
64
65 impl<R> Rng for R
66 where
67 R: TryRng<Error = Infallible> + ?Sized,
68 {
69 #[inline]
70 fn next_u32(&mut self) -> u32 {
71 match self.try_next_u32() {
72 Ok(x) => x,
73 }
74 }
75
76 #[inline]
77 fn next_u64(&mut self) -> u64 {
78 match self.try_next_u64() {
79 Ok(x) => x,
80 }
81 }
82
83 #[inline]
84 fn fill_bytes(&mut self, dst: &mut [u8]) {
85 match self.try_fill_bytes(dst) {
86 Ok(()) => (),
87 }
88 }
89 }
90
91 /// A marker trait for securely unpredictable infallible RNGs
92 ///
93 /// This is a convenient trait alias for <code>[TryCryptoRng]<Error = [Infallible]></code>.
94 /// It is equivalent to the trait sum <code>[Rng] + [TryCryptoRng]</code>.
95 pub trait CryptoRng: Rng + TryCryptoRng<Error = Infallible> {}
96
97 impl<R> CryptoRng for R where R: TryCryptoRng<Error = Infallible> + ?Sized {}
98
99 /// Base trait for random number generators and random data sources
100 ///
101 /// This trait provides a base interface designed to support efficient usage of
102 /// (`u32`, `u64`) word generators, block generators and random data sources.
103 /// There is no required relationship between the output of each method or any
104 /// requirement to use all generated random bits; for example an implementation
105 /// of [`try_fill_bytes`](Self::try_fill_bytes) may discard some generated bytes
106 /// to avoid storing a partially used word or block.
107 ///
108 /// # Requirements
109 ///
110 /// ### Quality and length
111 ///
112 /// Implementions should produce bits uniformly: each output value should be
113 /// equally likely, without observable patterns in successive outputs or
114 /// between the output streams of multiple instances of an implementation using
115 /// different seeds or streams (where supported by the implementation).
116 ///
117 /// Pathological implementations (e.g. constant or counting generators which
118 /// rarely change some bits) may cause issues in consumers of random data, for
119 /// example dead-locks in rejection samplers and obviously non-random output
120 /// (e.g. a counting generator may result in apparently-constant output from a
121 /// uniform-ranged distribution).
122 ///
123 /// Cryptographically unpredictable output is not a requirement of this trait,
124 /// but is a requirement of [`TryCryptoRng`].
125 ///
126 /// In practice, most implementations are pseudo-random number generators with a
127 /// finite *period* or *cycle length*, and (among non-cryptographic PRNGs)
128 /// statistical anomalies may appear long before a cycle occurs. An
129 /// implementation should ensure its period is sufficiently long that no
130 /// anomalies are likely to appear in usage and/or document its limitations.
131 ///
132 /// For more on PRNG quality and period, see [The Rust Rand Book: Quality][0].
133 ///
134 /// [0]: https://rust-random.github.io/book/guide-rngs.html#quality
135 ///
136 /// ### Reproducibility
137 ///
138 /// Algorithmic generators implementing [`SeedableRng`] should normally have
139 /// *portable, reproducible* output, i.e. fix Endianness when converting values
140 /// to avoid platform differences, and avoid making any changes which affect
141 /// output (except by communicating that the release has breaking changes).
142 /// See also [The Rust Rand Book: Reproducibility][1].
143 ///
144 /// [1]: https://rust-random.github.io/book/crate-reprod.html
145 ///
146 /// # Usage
147 ///
148 /// Often, usage of the infallible trait [`Rng`] or its extension trait
149 /// [`rand::RngExt`] is preferred to direct usage of `TryRng`.
150 //
151 /// Many implementations of `TryRng` (those with <code>type Error = [Infallible][]</code>)
152 /// already implement [`Rng`]; in other cases [`UnwrapErr`] may be used to obtain
153 /// an implementation of [`Rng`].
154 ///
155 /// # Implementing `TryRng`
156 ///
157 /// Most algorithmic generators (i.e. pseudo-random number generators or PRNGs)
158 /// never fail; in this case type `Error` should be [`Infallible`]; in this case
159 /// trait `Rng` is implemented automatically. Cycling is not considered an
160 /// error.
161 ///
162 /// Small PRNGs often yield either `u32` or `u64` natively.
163 /// Module [`crate::utils`] provides utilities to help implement other methods.
164 ///
165 /// Byte sources may implement [`try_fill_bytes`](Self::try_fill_bytes)
166 /// natively.
167 /// Module [`crate::utils`] provides utilities to help implement other methods.
168 ///
169 /// Block generators (which produce `[u32; N]` or `[u64; N]` for some fixed `N`)
170 /// should make use of the [`crate::block`] module.
171 ///
172 /// With regards to other traits:
173 ///
174 /// - **Do not** implement [`Default`] for seedable pseudorandom generators,
175 /// though the trait may be implemented for stateless interfaces and
176 /// auto-seeding generators.
177 /// - **Do** implement [`SeedableRng`] for seedable pseudorandom generators. See
178 /// [Reproducibility](#reproducibility) above.
179 /// - Implement [`Clone`] for non-cryptographic PRNGs but consider not doing so
180 /// for cryptographic generators to avoid the risk of key-stream duplication.
181 /// - **Do not** implement [`Copy`] since accidental copies may cause repeated
182 /// values.
183 /// - Implement [`Debug`](core::fmt::Debug), except that cryptographic PRNGs
184 /// should use a custom implementation which avoids leaking internal state (or
185 /// the subset of this derived from the key).
186 /// - [`Eq`] and [`PartialEq`] could be implemented, but are probably not useful.
187 ///
188 /// [`rand::RngExt`]: https://docs.rs/rand/latest/rand/trait.RngExt.html
189 pub trait TryRng {
190 /// The type returned in the event of a RNG error.
191 ///
192 /// Use type [`Infallible`] (re-exported by `rand_core`) for infallible implementations.
193 type Error: core::error::Error;
194
195 /// Return the next random `u32`.
196 fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
197 /// Return the next random `u64`.
198 fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
199 /// Fill `dst` entirely with random data.
200 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
201 }
202
203 impl<R: DerefMut> TryRng for R
204 where
205 R::Target: TryRng,
206 {
207 type Error = <R::Target as TryRng>::Error;
208
209 #[inline]
210 fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
211 self.deref_mut().try_next_u32()
212 }
213
214 #[inline]
215 fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
216 self.deref_mut().try_next_u64()
217 }
218
219 #[inline]
220 fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
221 self.deref_mut().try_fill_bytes(dst)
222 }
223 }
224
225 /// A marker trait over [`TryRng`] for securely unpredictable RNGs
226 ///
227 /// This marker trait indicates that the implementing generator is intended,
228 /// when correctly seeded and protected from side-channel attacks such as a
229 /// leaking of state, to be a cryptographically secure generator. This trait is
230 /// provided as a tool to aid review of cryptographic code, but does not by
231 /// itself guarantee suitability for cryptographic applications.
232 ///
233 /// Formally, a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
234 /// should satisfy an additional property over other generators: assuming that
235 /// the generator has been appropriately seeded and has unknown state, then
236 /// given the first *k* bits of an algorithm's output
237 /// sequence, it should not be possible using polynomial-time algorithms to
238 /// predict the next bit with probability significantly greater than 50%.
239 ///
240 /// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
241 /// state is revealed, it will not be computationally-feasible to reconstruct
242 /// prior output values. This property is not required by `CryptoRng`.
243 ///
244 /// Implementors of `TryCryptoRng` should only implement [`Default`] if a
245 /// default-constructed instance is itself a secure generator, for example
246 /// [`getrandom::SysRng`] which is a stateless interface.
247 ///
248 /// [`getrandom::SysRng`]: https://docs.rs/getrandom/latest/getrandom/struct.SysRng.html
249 pub trait TryCryptoRng: TryRng {}
250
251 impl<R: DerefMut> TryCryptoRng for R where R::Target: TryCryptoRng {}
252
253 /// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`Rng`] is the
254 /// replacement.
255 // TODO: remove prior to v1.x.
256 #[deprecated(since = "0.10.0", note = "use `Rng` instead")]
257 pub trait RngCore: Rng {}
258 #[allow(deprecated)]
259 impl<R: Rng> RngCore for R {}
260
261 /// DEPRECATED: stub trait to print a deprecation warning and aid discovering that [`TryRng`] is the
262 /// replacement.
263 // TODO: remove prior to v1.x.
264 #[deprecated(since = "0.10.0", note = "use `TryRng` instead")]
265 pub trait TryRngCore: TryRng {
266 /// Error type.
267 type Error: core::error::Error;
268 }
269 #[allow(deprecated)]
270 impl<R: TryRng> TryRngCore for R {
271 type Error = R::Error;
272 }