Skip to content

Commit 6a06056

Browse files
authored
rand_core: introduce an UnwrapMut wrapper (#1589)
1 parent 8929123 commit 6a06056

File tree

2 files changed

+34
-0
lines changed

2 files changed

+34
-0
lines changed

rand_core/CHANGELOG.md

+5
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

+29
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,11 @@ pub trait TryRngCore {
236236
UnwrapErr(self)
237237
}
238238

239+
/// Wrap RNG with the [`UnwrapMut`] wrapper.
240+
fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self> {
241+
UnwrapMut(self)
242+
}
243+
239244
/// Convert an [`RngCore`] to a [`RngReadAdapter`].
240245
#[cfg(feature = "std")]
241246
fn read_adapter(&mut self) -> RngReadAdapter<'_, Self>
@@ -311,6 +316,30 @@ impl<R: TryRngCore> RngCore for UnwrapErr<R> {
311316

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

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

0 commit comments

Comments
 (0)