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