@@ -208,6 +208,35 @@ pub trait RngCore {
208
208
/// [`BlockRngCore`]: block::BlockRngCore
209
209
pub trait CryptoRng { }
210
210
211
+ /// An extension trait that is automatically implemented for any type
212
+ /// implementing [`RngCore`] and [`CryptoRng`].
213
+ ///
214
+ /// It may be used as a trait object, and supports upcasting to [`RngCore`] via
215
+ /// the [`CryptoRngCore::as_rngcore`] method.
216
+ ///
217
+ /// # Example
218
+ ///
219
+ /// ```
220
+ /// use rand_core::CryptoRngCore;
221
+ ///
222
+ /// #[allow(unused)]
223
+ /// fn make_token(rng: &mut dyn CryptoRngCore) -> [u8; 32] {
224
+ /// let mut buf = [0u8; 32];
225
+ /// rng.fill_bytes(&mut buf);
226
+ /// buf
227
+ /// }
228
+ /// ```
229
+ pub trait CryptoRngCore : RngCore {
230
+ /// Upcast to an [`RngCore`] trait object.
231
+ fn as_rngcore ( & mut self ) -> & mut dyn RngCore ;
232
+ }
233
+
234
+ impl < T : CryptoRng + RngCore > CryptoRngCore for T {
235
+ fn as_rngcore ( & mut self ) -> & mut dyn RngCore {
236
+ self
237
+ }
238
+ }
239
+
211
240
/// A random number generator that can be explicitly seeded.
212
241
///
213
242
/// This trait encapsulates the low-level functionality common to all
@@ -448,10 +477,10 @@ impl std::io::Read for dyn RngCore {
448
477
}
449
478
}
450
479
451
- // Implement `CryptoRng` for references to an `CryptoRng`.
480
+ // Implement `CryptoRng` for references to a `CryptoRng`.
452
481
impl < ' a , R : CryptoRng + ?Sized > CryptoRng for & ' a mut R { }
453
482
454
- // Implement `CryptoRng` for boxed references to an `CryptoRng`.
483
+ // Implement `CryptoRng` for boxed references to a `CryptoRng`.
455
484
#[ cfg( feature = "alloc" ) ]
456
485
impl < R : CryptoRng + ?Sized > CryptoRng for Box < R > { }
457
486
0 commit comments