Skip to content
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

Add CryptoRngCore to support CryptoRng trait objects #1187

Merged
merged 5 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from 3 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.upcast();
let r2 = rng.next_u64();
assert_ne!(r1, r2);
}
}
18 changes: 16 additions & 2 deletions rand_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,20 @@ pub trait RngCore {
/// [`BlockRngCore`]: block::BlockRngCore
pub trait CryptoRng {}

/// An extension trait to support trait objects that implement [`RngCore`] and
/// [`CryptoRng`]. Upcasting to [`RngCore`] is supported via the
/// [`CryptoRngCore::upcast`] method.
dhardy marked this conversation as resolved.
Show resolved Hide resolved
pub trait CryptoRngCore: RngCore {
/// Upcast to an [`RngCore`] trait object.
fn upcast(&mut self) -> &mut dyn RngCore;
vks marked this conversation as resolved.
Show resolved Hide resolved
}

impl<T: CryptoRng + RngCore> CryptoRngCore for T {
fn upcast(&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 +462,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