Skip to content

Commit 4f560d0

Browse files
committed
rand_core: introduce an UnwrapRef wrapper
This is used when a method takes in a `&mut impl TryRngCore` but the inner method requires an `&mut impl RngCore`. An `UnwrapErr` can not be used as it requires ownership of the rng.
1 parent 06b1642 commit 4f560d0

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

rand_core/CHANGELOG.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,11 @@ All notable changes to this project will be documented in this file.
44
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
55
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
66

7+
## Unreleased
8+
9+
### API changes
10+
- Add `TryRngCore::unwrap_ref` to only take a mutable reference of the rng (#1589)
11+
712
## [0.9.0] - 2025-01-27
813
### Dependencies and features
914
- 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`

rand_core/src/lib.rs

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,14 @@ pub trait TryRngCore {
236236
UnwrapErr(self)
237237
}
238238

239+
/// Wrap RNG with the [`UnwrapRef`] wrapper.
240+
fn unwrap_mut<'r>(&'r mut self) -> UnwrapRef<'r, Self>
241+
where
242+
Self: Sized,
243+
{
244+
UnwrapRef(self)
245+
}
246+
239247
/// Convert an [`RngCore`] to a [`RngReadAdapter`].
240248
#[cfg(feature = "std")]
241249
fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
@@ -311,6 +319,30 @@ impl<R: TryRngCore> RngCore for UnwrapErr<R> {
311319

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

322+
/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
323+
/// by panicking on potential errors.
324+
#[derive(Debug, Eq, PartialEq, Hash)]
325+
pub struct UnwrapRef<'r, R: TryRngCore>(pub &'r mut R);
326+
327+
impl<R: TryRngCore> RngCore for UnwrapRef<'_, R> {
328+
#[inline]
329+
fn next_u32(&mut self) -> u32 {
330+
self.0.try_next_u32().unwrap()
331+
}
332+
333+
#[inline]
334+
fn next_u64(&mut self) -> u64 {
335+
self.0.try_next_u64().unwrap()
336+
}
337+
338+
#[inline]
339+
fn fill_bytes(&mut self, dst: &mut [u8]) {
340+
self.0.try_fill_bytes(dst).unwrap()
341+
}
342+
}
343+
344+
impl<R: TryCryptoRng> CryptoRng for UnwrapRef<'_, R> {}
345+
314346
/// A random number generator that can be explicitly seeded.
315347
///
316348
/// This trait encapsulates the low-level functionality common to all

0 commit comments

Comments
 (0)