@@ -208,6 +208,35 @@ pub trait RngCore {
208208/// [`BlockRngCore`]: block::BlockRngCore
209209pub trait CryptoRng { }
210210
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+
211240/// A random number generator that can be explicitly seeded.
212241///
213242/// This trait encapsulates the low-level functionality common to all
@@ -448,10 +477,10 @@ impl std::io::Read for dyn RngCore {
448477 }
449478}
450479
451- // Implement `CryptoRng` for references to an `CryptoRng`.
480+ // Implement `CryptoRng` for references to a `CryptoRng`.
452481impl < ' a , R : CryptoRng + ?Sized > CryptoRng for & ' a mut R { }
453482
454- // Implement `CryptoRng` for boxed references to an `CryptoRng`.
483+ // Implement `CryptoRng` for boxed references to a `CryptoRng`.
455484#[ cfg( feature = "alloc" ) ]
456485impl < R : CryptoRng + ?Sized > CryptoRng for Box < R > { }
457486
0 commit comments