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

rand_core: introduce an UnwrapMut wrapper #1589

Merged
merged 1 commit into from
Feb 16, 2025
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
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