Skip to content

Add CryptoRngCore to support CryptoRng trait objects #1187

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions rand_chacha/src/chacha.rs
Original file line number Diff line number Diff line change
Expand Up @@ -623,4 +623,15 @@ mod test {
rng.set_word_pos(0);
assert_eq!(rng.get_word_pos(), 0);
}

#[test]
fn test_trait_objects() {
use rand_core::CryptoRngCore;

let rng = &mut ChaChaRng::from_seed(Default::default()) as &mut dyn CryptoRngCore;
let r1 = rng.next_u64();
let rng: &mut dyn RngCore = rng.as_rngcore();
let r2 = rng.next_u64();
assert_ne!(r1, r2);
}
}
33 changes: 31 additions & 2 deletions rand_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,35 @@ pub trait RngCore {
/// [`BlockRngCore`]: block::BlockRngCore
pub trait CryptoRng {}

/// An extension trait that is automatically implemented for any type
/// implementing [`RngCore`] and [`CryptoRng`].
///
/// It may be used as a trait object, and supports upcasting to [`RngCore`] via
/// the [`CryptoRngCore::as_rngcore`] method.
///
/// # Example
///
/// ```
/// use rand_core::CryptoRngCore;
///
/// #[allow(unused)]
/// fn make_token(rng: &mut dyn CryptoRngCore) -> [u8; 32] {
/// let mut buf = [0u8; 32];
/// rng.fill_bytes(&mut buf);
/// buf
/// }
/// ```
pub trait CryptoRngCore: RngCore {
/// Upcast to an [`RngCore`] trait object.
fn as_rngcore(&mut self) -> &mut dyn RngCore;
}

impl<T: CryptoRng + RngCore> CryptoRngCore for T {
fn as_rngcore(&mut self) -> &mut dyn RngCore {
self
}
}

/// A random number generator that can be explicitly seeded.
///
/// This trait encapsulates the low-level functionality common to all
Expand Down Expand Up @@ -448,10 +477,10 @@ impl std::io::Read for dyn RngCore {
}
}

// Implement `CryptoRng` for references to an `CryptoRng`.
// Implement `CryptoRng` for references to a `CryptoRng`.
impl<'a, R: CryptoRng + ?Sized> CryptoRng for &'a mut R {}

// Implement `CryptoRng` for boxed references to an `CryptoRng`.
// Implement `CryptoRng` for boxed references to a `CryptoRng`.
#[cfg(feature = "alloc")]
impl<R: CryptoRng + ?Sized> CryptoRng for Box<R> {}

Expand Down