Skip to content

Commit

Permalink
rand_core: introduce an UnwrapMut wrapper (#1589)
Browse files Browse the repository at this point in the history
  • Loading branch information
baloo authored Feb 16, 2025
1 parent 8929123 commit 6a06056
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 0 deletions.
5 changes: 5 additions & 0 deletions rand_core/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`
Expand Down
29 changes: 29 additions & 0 deletions rand_core/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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>
Expand Down Expand Up @@ -311,6 +316,30 @@ impl<R: TryRngCore> RngCore for UnwrapErr<R> {

impl<R: TryCryptoRng> CryptoRng for UnwrapErr<R> {}

/// 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<R: TryRngCore> 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<R: TryCryptoRng> CryptoRng for UnwrapMut<'_, R> {}

/// A random number generator that can be explicitly seeded.
///
/// This trait encapsulates the low-level functionality common to all
Expand Down

0 comments on commit 6a06056

Please sign in to comment.