diff --git a/rand_core/CHANGELOG.md b/rand_core/CHANGELOG.md index f13de92d1a..66cd46f49c 100644 --- a/rand_core/CHANGELOG.md +++ b/rand_core/CHANGELOG.md @@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). +## Unreleased + +### API changes +- Add `TryRngCore::unwrap_ref` to only take a mutable reference of the rng (#1589) + ## [0.9.0] - 2025-01-27 ### Dependencies and features - Bump the MSRV to 1.63.0 (#1207, #1246, #1269, #1341, #1416, #1536); note that 1.60.0 may work for dependents when using `--ignore-rust-version` diff --git a/rand_core/src/lib.rs b/rand_core/src/lib.rs index 874a086504..0336c5bc2a 100644 --- a/rand_core/src/lib.rs +++ b/rand_core/src/lib.rs @@ -236,6 +236,11 @@ pub trait TryRngCore { UnwrapErr(self) } + /// Wrap RNG with the [`UnwrapMut`] wrapper. + fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self> { + UnwrapMut(self) + } + /// Convert an [`RngCore`] to a [`RngReadAdapter`]. #[cfg(feature = "std")] fn read_adapter(&mut self) -> RngReadAdapter<'_, Self> @@ -311,6 +316,30 @@ impl RngCore for UnwrapErr { impl CryptoRng for UnwrapErr {} +/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`] +/// by panicking on potential errors. +#[derive(Debug, Eq, PartialEq, Hash)] +pub struct UnwrapMut<'r, R: TryRngCore + ?Sized>(pub &'r mut R); + +impl RngCore for UnwrapMut<'_, R> { + #[inline] + fn next_u32(&mut self) -> u32 { + self.0.try_next_u32().unwrap() + } + + #[inline] + fn next_u64(&mut self) -> u64 { + self.0.try_next_u64().unwrap() + } + + #[inline] + fn fill_bytes(&mut self, dst: &mut [u8]) { + self.0.try_fill_bytes(dst).unwrap() + } +} + +impl CryptoRng for UnwrapMut<'_, R> {} + /// A random number generator that can be explicitly seeded. /// /// This trait encapsulates the low-level functionality common to all