rand_core/
lib.rs

1// Hide badges from generated docs
2//! <style> .badges { display: none; } </style>
3
4#![no_std]
5#![doc = include_str!("../README.md")]
6#![doc(
7    html_logo_url = "https://www.rust-lang.org/logos/rust-logo-128x128-blk.png",
8    html_favicon_url = "https://www.rust-lang.org/favicon.ico"
9)]
10#![deny(
11    missing_docs,
12    missing_debug_implementations,
13    clippy::undocumented_unsafe_blocks
14)]
15
16use core::{fmt, ops::DerefMut};
17
18pub mod block;
19pub mod utils;
20mod word;
21
22/// Implementation-level interface for RNGs
23///
24/// This trait encapsulates the low-level functionality common to all
25/// generators, and is the "back end", to be implemented by generators.
26/// End users should normally use the [`rand::Rng`] trait
27/// which is automatically implemented for every type implementing `RngCore`.
28///
29/// Three different methods for generating random data are provided since the
30/// optimal implementation of each is dependent on the type of generator. There
31/// is no required relationship between the output of each; e.g. many
32/// implementations of [`fill_bytes`] consume a whole number of `u32` or `u64`
33/// values and drop any remaining unused bytes. The same can happen with the
34/// [`next_u32`] and [`next_u64`] methods, implementations may discard some
35/// random bits for efficiency.
36///
37/// # Properties of a generator
38///
39/// Implementers should produce bits uniformly. Pathological RNGs (e.g. constant
40/// or counting generators which rarely change some bits) may cause issues in
41/// consumers of random data, for example dead-locks in rejection samplers and
42/// obviously non-random output (e.g. a counting generator may result in
43/// apparently-constant output from a uniform-ranged distribution).
44///
45/// Algorithmic generators implementing [`SeedableRng`] should normally have
46/// *portable, reproducible* output, i.e. fix Endianness when converting values
47/// to avoid platform differences, and avoid making any changes which affect
48/// output (except by communicating that the release has breaking changes).
49///
50/// # Implementing `RngCore`
51///
52/// Typically an RNG will implement only one of the methods available
53/// in this trait directly, then use the helper functions from the
54/// [`utils`] module to implement the other methods.
55///
56/// Note that implementors of [`RngCore`] also automatically implement
57/// the [`TryRngCore`] trait with the `Error` associated type being
58/// equal to [`Infallible`].
59///
60/// It is recommended that implementations also implement:
61///
62/// - `Debug` with a custom implementation which *does not* print any internal
63///   state (at least, [`CryptoRng`]s should not risk leaking state through
64///   `Debug`).
65/// - `Serialize` and `Deserialize` (from Serde), preferably making Serde
66///   support optional at the crate level in PRNG libs.
67/// - `Clone`, if possible.
68/// - *never* implement `Copy` (accidental copies may cause repeated values).
69/// - *do not* implement `Default` for pseudorandom generators, but instead
70///   implement [`SeedableRng`], to guide users towards proper seeding.
71///   External / hardware RNGs can choose to implement `Default`.
72/// - `Eq` and `PartialEq` could be implemented, but are probably not useful.
73///
74/// [`rand::Rng`]: https://docs.rs/rand/latest/rand/trait.Rng.html
75/// [`fill_bytes`]: RngCore::fill_bytes
76/// [`next_u32`]: RngCore::next_u32
77/// [`next_u64`]: RngCore::next_u64
78/// [`Infallible`]: core::convert::Infallible
79pub trait RngCore {
80    /// Return the next random `u32`.
81    fn next_u32(&mut self) -> u32;
82
83    /// Return the next random `u64`.
84    fn next_u64(&mut self) -> u64;
85
86    /// Fill `dest` with random data.
87    ///
88    /// This method should guarantee that `dest` is entirely filled
89    /// with new data, and may panic if this is impossible
90    /// (e.g. reading past the end of a file that is being used as the
91    /// source of randomness).
92    fn fill_bytes(&mut self, dst: &mut [u8]);
93}
94
95impl<T: DerefMut> RngCore for T
96where
97    T::Target: RngCore,
98{
99    #[inline]
100    fn next_u32(&mut self) -> u32 {
101        self.deref_mut().next_u32()
102    }
103
104    #[inline]
105    fn next_u64(&mut self) -> u64 {
106        self.deref_mut().next_u64()
107    }
108
109    #[inline]
110    fn fill_bytes(&mut self, dst: &mut [u8]) {
111        self.deref_mut().fill_bytes(dst);
112    }
113}
114
115/// A marker trait over [`RngCore`] for securely unpredictable RNGs
116///
117/// This marker trait indicates that the implementing generator is intended,
118/// when correctly seeded and protected from side-channel attacks such as a
119/// leaking of state, to be a cryptographically secure generator. This trait is
120/// provided as a tool to aid review of cryptographic code, but does not by
121/// itself guarantee suitability for cryptographic applications.
122///
123/// Implementors of `CryptoRng` automatically implement the [`TryCryptoRng`]
124/// trait.
125///
126/// Implementors of `CryptoRng` should only implement [`Default`] if the
127/// `default()` instances are themselves secure generators: for example if the
128/// implementing type is a stateless interface over a secure external generator
129/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
130///
131/// Formally, a CSPRNG (Cryptographically Secure Pseudo-Random Number Generator)
132/// should satisfy an additional property over other generators: assuming that
133/// the generator has been appropriately seeded and has unknown state, then
134/// given the first *k* bits of an algorithm's output
135/// sequence, it should not be possible using polynomial-time algorithms to
136/// predict the next bit with probability significantly greater than 50%.
137///
138/// An optional property of CSPRNGs is backtracking resistance: if the CSPRNG's
139/// state is revealed, it will not be computationally-feasible to reconstruct
140/// prior output values. This property is not required by `CryptoRng`.
141///
142/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
143pub trait CryptoRng: RngCore {}
144
145impl<T: DerefMut> CryptoRng for T where T::Target: CryptoRng {}
146
147/// A potentially fallible variant of [`RngCore`]
148///
149/// This trait is a generalization of [`RngCore`] to support potentially-
150/// fallible IO-based generators such as [`OsRng`].
151///
152/// All implementations of [`RngCore`] automatically support this `TryRngCore`
153/// trait, using [`Infallible`][core::convert::Infallible] as the associated
154/// `Error` type.
155///
156/// An implementation of this trait may be made compatible with code requiring
157/// an [`RngCore`] through [`TryRngCore::unwrap_err`]. The resulting RNG will
158/// panic in case the underlying fallible RNG yields an error.
159///
160/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
161pub trait TryRngCore {
162    /// The type returned in the event of a RNG error.
163    type Error: fmt::Debug + fmt::Display;
164
165    /// Return the next random `u32`.
166    fn try_next_u32(&mut self) -> Result<u32, Self::Error>;
167    /// Return the next random `u64`.
168    fn try_next_u64(&mut self) -> Result<u64, Self::Error>;
169    /// Fill `dest` entirely with random data.
170    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error>;
171
172    /// Wrap RNG with the [`UnwrapErr`] wrapper.
173    fn unwrap_err(self) -> UnwrapErr<Self>
174    where
175        Self: Sized,
176    {
177        UnwrapErr(self)
178    }
179
180    /// Wrap RNG with the [`UnwrapMut`] wrapper.
181    fn unwrap_mut(&mut self) -> UnwrapMut<'_, Self> {
182        UnwrapMut(self)
183    }
184}
185
186// Note that, unfortunately, this blanket impl prevents us from implementing
187// `TryRngCore` for types which can be dereferenced to `TryRngCore`, i.e. `TryRngCore`
188// will not be automatically implemented for `&mut R`, `Box<R>`, etc.
189impl<R: RngCore + ?Sized> TryRngCore for R {
190    type Error = core::convert::Infallible;
191
192    #[inline]
193    fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
194        Ok(self.next_u32())
195    }
196
197    #[inline]
198    fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
199        Ok(self.next_u64())
200    }
201
202    #[inline]
203    fn try_fill_bytes(&mut self, dst: &mut [u8]) -> Result<(), Self::Error> {
204        self.fill_bytes(dst);
205        Ok(())
206    }
207}
208
209/// A marker trait over [`TryRngCore`] for securely unpredictable RNGs
210///
211/// This trait is like [`CryptoRng`] but for the trait [`TryRngCore`].
212///
213/// This marker trait indicates that the implementing generator is intended,
214/// when correctly seeded and protected from side-channel attacks such as a
215/// leaking of state, to be a cryptographically secure generator. This trait is
216/// provided as a tool to aid review of cryptographic code, but does not by
217/// itself guarantee suitability for cryptographic applications.
218///
219/// Implementors of `TryCryptoRng` should only implement [`Default`] if the
220/// `default()` instances are themselves secure generators: for example if the
221/// implementing type is a stateless interface over a secure external generator
222/// (like [`OsRng`]) or if the `default()` instance uses a strong, fresh seed.
223///
224/// [`OsRng`]: https://docs.rs/rand/latest/rand/rngs/struct.OsRng.html
225pub trait TryCryptoRng: TryRngCore {}
226
227impl<R: CryptoRng + ?Sized> TryCryptoRng for R {}
228
229/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
230/// by panicking on potential errors.
231#[derive(Debug, Default, Clone, Copy, Eq, PartialEq, Hash)]
232pub struct UnwrapErr<R: TryRngCore>(pub R);
233
234impl<R: TryRngCore> RngCore for UnwrapErr<R> {
235    #[inline]
236    fn next_u32(&mut self) -> u32 {
237        self.0.try_next_u32().unwrap()
238    }
239
240    #[inline]
241    fn next_u64(&mut self) -> u64 {
242        self.0.try_next_u64().unwrap()
243    }
244
245    #[inline]
246    fn fill_bytes(&mut self, dst: &mut [u8]) {
247        self.0.try_fill_bytes(dst).unwrap()
248    }
249}
250
251impl<R: TryCryptoRng> CryptoRng for UnwrapErr<R> {}
252
253/// Wrapper around [`TryRngCore`] implementation which implements [`RngCore`]
254/// by panicking on potential errors.
255#[derive(Debug, Eq, PartialEq, Hash)]
256pub struct UnwrapMut<'r, R: TryRngCore + ?Sized>(pub &'r mut R);
257
258impl<'r, R: TryRngCore + ?Sized> UnwrapMut<'r, R> {
259    /// Reborrow with a new lifetime
260    ///
261    /// Rust allows references like `&T` or `&mut T` to be "reborrowed" through
262    /// coercion: essentially, the pointer is copied under a new, shorter, lifetime.
263    /// Until rfcs#1403 lands, reborrows on user types require a method call.
264    #[inline(always)]
265    pub fn re<'b>(&'b mut self) -> UnwrapMut<'b, R>
266    where
267        'r: 'b,
268    {
269        UnwrapMut(self.0)
270    }
271}
272
273impl<R: TryRngCore + ?Sized> RngCore for UnwrapMut<'_, R> {
274    #[inline]
275    fn next_u32(&mut self) -> u32 {
276        self.0.try_next_u32().unwrap()
277    }
278
279    #[inline]
280    fn next_u64(&mut self) -> u64 {
281        self.0.try_next_u64().unwrap()
282    }
283
284    #[inline]
285    fn fill_bytes(&mut self, dst: &mut [u8]) {
286        self.0.try_fill_bytes(dst).unwrap()
287    }
288}
289
290impl<R: TryCryptoRng + ?Sized> CryptoRng for UnwrapMut<'_, R> {}
291
292/// A random number generator that can be explicitly seeded.
293///
294/// This trait encapsulates the low-level functionality common to all
295/// pseudo-random number generators (PRNGs, or algorithmic generators).
296///
297/// A generator implementing `SeedableRng` will usually be deterministic, but
298/// beware that portability and reproducibility of results **is not implied**.
299/// Refer to documentation of the generator, noting that generators named after
300/// a specific algorithm are usually tested for reproducibility against a
301/// reference vector, while `SmallRng` and `StdRng` specifically opt out of
302/// reproducibility guarantees.
303///
304/// [`rand`]: https://docs.rs/rand
305pub trait SeedableRng: Sized {
306    /// Seed type, which is restricted to types mutably-dereferenceable as `u8`
307    /// arrays (we recommend `[u8; N]` for some `N`).
308    ///
309    /// It is recommended to seed PRNGs with a seed of at least circa 100 bits,
310    /// which means an array of `[u8; 12]` or greater to avoid picking RNGs with
311    /// partially overlapping periods.
312    ///
313    /// For cryptographic RNG's a seed of 256 bits is recommended, `[u8; 32]`.
314    ///
315    ///
316    /// # Implementing `SeedableRng` for RNGs with large seeds
317    ///
318    /// Note that [`Default`] is not implemented for large arrays `[u8; N]` with
319    /// `N` > 32. To be able to implement the traits required by `SeedableRng`
320    /// for RNGs with such large seeds, the newtype pattern can be used:
321    ///
322    /// ```
323    /// use rand_core::SeedableRng;
324    ///
325    /// const N: usize = 64;
326    /// #[derive(Clone)]
327    /// pub struct MyRngSeed(pub [u8; N]);
328    /// # #[allow(dead_code)]
329    /// pub struct MyRng(MyRngSeed);
330    ///
331    /// impl Default for MyRngSeed {
332    ///     fn default() -> MyRngSeed {
333    ///         MyRngSeed([0; N])
334    ///     }
335    /// }
336    ///
337    /// impl AsRef<[u8]> for MyRngSeed {
338    ///     fn as_ref(&self) -> &[u8] {
339    ///         &self.0
340    ///     }
341    /// }
342    ///
343    /// impl AsMut<[u8]> for MyRngSeed {
344    ///     fn as_mut(&mut self) -> &mut [u8] {
345    ///         &mut self.0
346    ///     }
347    /// }
348    ///
349    /// impl SeedableRng for MyRng {
350    ///     type Seed = MyRngSeed;
351    ///
352    ///     fn from_seed(seed: MyRngSeed) -> MyRng {
353    ///         MyRng(seed)
354    ///     }
355    /// }
356    /// ```
357    type Seed: Clone + Default + AsRef<[u8]> + AsMut<[u8]>;
358
359    /// Create a new PRNG using the given seed.
360    ///
361    /// PRNG implementations are allowed to assume that bits in the seed are
362    /// well distributed. That means usually that the number of one and zero
363    /// bits are roughly equal, and values like 0, 1 and (size - 1) are unlikely.
364    /// Note that many non-cryptographic PRNGs will show poor quality output
365    /// if this is not adhered to. If you wish to seed from simple numbers, use
366    /// `seed_from_u64` instead.
367    ///
368    /// All PRNG implementations should be reproducible unless otherwise noted:
369    /// given a fixed `seed`, the same sequence of output should be produced
370    /// on all runs, library versions and architectures (e.g. check endianness).
371    /// Any "value-breaking" changes to the generator should require bumping at
372    /// least the minor version and documentation of the change.
373    ///
374    /// It is not required that this function yield the same state as a
375    /// reference implementation of the PRNG given equivalent seed; if necessary
376    /// another constructor replicating behaviour from a reference
377    /// implementation can be added.
378    ///
379    /// PRNG implementations should make sure `from_seed` never panics. In the
380    /// case that some special values (like an all zero seed) are not viable
381    /// seeds it is preferable to map these to alternative constant value(s),
382    /// for example `0xBAD5EEDu32` or `0x0DDB1A5E5BAD5EEDu64` ("odd biases? bad
383    /// seed"). This is assuming only a small number of values must be rejected.
384    fn from_seed(seed: Self::Seed) -> Self;
385
386    /// Create a new PRNG using a `u64` seed.
387    ///
388    /// This is a convenience-wrapper around `from_seed` to allow construction
389    /// of any `SeedableRng` from a simple `u64` value. It is designed such that
390    /// low Hamming Weight numbers like 0 and 1 can be used and should still
391    /// result in good, independent seeds to the PRNG which is returned.
392    ///
393    /// This **is not suitable for cryptography**, as should be clear given that
394    /// the input size is only 64 bits.
395    ///
396    /// Implementations for PRNGs *may* provide their own implementations of
397    /// this function, but the default implementation should be good enough for
398    /// all purposes. *Changing* the implementation of this function should be
399    /// considered a value-breaking change.
400    fn seed_from_u64(mut state: u64) -> Self {
401        // We use PCG32 to generate a u32 sequence, and copy to the seed
402        fn pcg32(state: &mut u64) -> [u8; 4] {
403            const MUL: u64 = 6364136223846793005;
404            const INC: u64 = 11634580027462260723;
405
406            // We advance the state first (to get away from the input value,
407            // in case it has low Hamming Weight).
408            *state = state.wrapping_mul(MUL).wrapping_add(INC);
409            let state = *state;
410
411            // Use PCG output function with to_le to generate x:
412            let xorshifted = (((state >> 18) ^ state) >> 27) as u32;
413            let rot = (state >> 59) as u32;
414            let x = xorshifted.rotate_right(rot);
415            x.to_le_bytes()
416        }
417
418        let mut seed = Self::Seed::default();
419        let mut iter = seed.as_mut().chunks_exact_mut(4);
420        for chunk in &mut iter {
421            chunk.copy_from_slice(&pcg32(&mut state));
422        }
423        let rem = iter.into_remainder();
424        if !rem.is_empty() {
425            rem.copy_from_slice(&pcg32(&mut state)[..rem.len()]);
426        }
427
428        Self::from_seed(seed)
429    }
430
431    /// Create a new PRNG seeded from an infallible `Rng`.
432    ///
433    /// This may be useful when needing to rapidly seed many PRNGs from a master
434    /// PRNG, and to allow forking of PRNGs. It may be considered deterministic.
435    ///
436    /// The master PRNG should be at least as high quality as the child PRNGs.
437    /// When seeding non-cryptographic child PRNGs, we recommend using a
438    /// different algorithm for the master PRNG (ideally a CSPRNG) to avoid
439    /// correlations between the child PRNGs. If this is not possible (e.g.
440    /// forking using small non-crypto PRNGs) ensure that your PRNG has a good
441    /// mixing function on the output or consider use of a hash function with
442    /// `from_seed`.
443    ///
444    /// Note that seeding `XorShiftRng` from another `XorShiftRng` provides an
445    /// extreme example of what can go wrong: the new PRNG will be a clone
446    /// of the parent.
447    ///
448    /// PRNG implementations are allowed to assume that a good RNG is provided
449    /// for seeding, and that it is cryptographically secure when appropriate.
450    /// As of `rand` 0.7 / `rand_core` 0.5, implementations overriding this
451    /// method should ensure the implementation satisfies reproducibility
452    /// (in prior versions this was not required).
453    ///
454    /// [`rand`]: https://docs.rs/rand
455    fn from_rng<R: RngCore + ?Sized>(rng: &mut R) -> Self {
456        let mut seed = Self::Seed::default();
457        rng.fill_bytes(seed.as_mut());
458        Self::from_seed(seed)
459    }
460
461    /// Create a new PRNG seeded from a potentially fallible `Rng`.
462    ///
463    /// See [`from_rng`][SeedableRng::from_rng] docs for more information.
464    fn try_from_rng<R: TryRngCore + ?Sized>(rng: &mut R) -> Result<Self, R::Error> {
465        let mut seed = Self::Seed::default();
466        rng.try_fill_bytes(seed.as_mut())?;
467        Ok(Self::from_seed(seed))
468    }
469
470    /// Fork this PRNG
471    ///
472    /// This creates a new PRNG from the current one by initializing a new one and
473    /// seeding it from the current one.
474    ///
475    /// This is useful when initializing a PRNG for a thread
476    fn fork(&mut self) -> Self
477    where
478        Self: RngCore,
479    {
480        Self::from_rng(self)
481    }
482
483    /// Fork this PRNG
484    ///
485    /// This creates a new PRNG from the current one by initializing a new one and
486    /// seeding it from the current one.
487    ///
488    /// This is useful when initializing a PRNG for a thread.
489    ///
490    /// This is the failable equivalent to [`SeedableRng::fork`]
491    fn try_fork(&mut self) -> Result<Self, Self::Error>
492    where
493        Self: TryRngCore,
494    {
495        Self::try_from_rng(self)
496    }
497}
498
499#[cfg(test)]
500mod test {
501    use super::*;
502
503    #[test]
504    fn test_seed_from_u64() {
505        struct SeedableNum(u64);
506        impl SeedableRng for SeedableNum {
507            type Seed = [u8; 8];
508
509            fn from_seed(seed: Self::Seed) -> Self {
510                let x: [u64; 1] = utils::read_words(&seed);
511                SeedableNum(x[0])
512            }
513        }
514
515        const N: usize = 8;
516        const SEEDS: [u64; N] = [0u64, 1, 2, 3, 4, 8, 16, -1i64 as u64];
517        let mut results = [0u64; N];
518        for (i, seed) in SEEDS.iter().enumerate() {
519            let SeedableNum(x) = SeedableNum::seed_from_u64(*seed);
520            results[i] = x;
521        }
522
523        for (i1, r1) in results.iter().enumerate() {
524            let weight = r1.count_ones();
525            // This is the binomial distribution B(64, 0.5), so chance of
526            // weight < 20 is binocdf(19, 64, 0.5) = 7.8e-4, and same for
527            // weight > 44.
528            assert!((20..=44).contains(&weight));
529
530            for (i2, r2) in results.iter().enumerate() {
531                if i1 == i2 {
532                    continue;
533                }
534                let diff_weight = (r1 ^ r2).count_ones();
535                assert!(diff_weight >= 20);
536            }
537        }
538
539        // value-breakage test:
540        assert_eq!(results[0], 5029875928683246316);
541    }
542
543    // A stub RNG.
544    struct SomeRng;
545
546    impl RngCore for SomeRng {
547        fn next_u32(&mut self) -> u32 {
548            unimplemented!()
549        }
550        fn next_u64(&mut self) -> u64 {
551            unimplemented!()
552        }
553        fn fill_bytes(&mut self, _: &mut [u8]) {
554            unimplemented!()
555        }
556    }
557
558    impl CryptoRng for SomeRng {}
559
560    #[test]
561    fn dyn_rngcore_to_tryrngcore() {
562        // Illustrates the need for `+ ?Sized` bound in `impl<R: RngCore> TryRngCore for R`.
563
564        // A method in another crate taking a fallible RNG
565        fn third_party_api(_rng: &mut (impl TryRngCore + ?Sized)) -> bool {
566            true
567        }
568
569        // A method in our crate requiring an infallible RNG
570        fn my_api(rng: &mut dyn RngCore) -> bool {
571            // We want to call the method above
572            third_party_api(rng)
573        }
574
575        assert!(my_api(&mut SomeRng));
576    }
577
578    #[test]
579    fn dyn_cryptorng_to_trycryptorng() {
580        // Illustrates the need for `+ ?Sized` bound in `impl<R: CryptoRng> TryCryptoRng for R`.
581
582        // A method in another crate taking a fallible RNG
583        fn third_party_api(_rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
584            true
585        }
586
587        // A method in our crate requiring an infallible RNG
588        fn my_api(rng: &mut dyn CryptoRng) -> bool {
589            // We want to call the method above
590            third_party_api(rng)
591        }
592
593        assert!(my_api(&mut SomeRng));
594    }
595
596    #[test]
597    fn dyn_unwrap_mut_tryrngcore() {
598        // Illustrates the need for `+ ?Sized` bound in
599        // `impl<R: TryRngCore> RngCore for UnwrapMut<'_, R>`.
600
601        fn third_party_api(_rng: &mut impl RngCore) -> bool {
602            true
603        }
604
605        fn my_api(rng: &mut (impl TryRngCore + ?Sized)) -> bool {
606            let mut infallible_rng = rng.unwrap_mut();
607            third_party_api(&mut infallible_rng)
608        }
609
610        assert!(my_api(&mut SomeRng));
611    }
612
613    #[test]
614    fn dyn_unwrap_mut_trycryptorng() {
615        // Illustrates the need for `+ ?Sized` bound in
616        // `impl<R: TryCryptoRng> CryptoRng for UnwrapMut<'_, R>`.
617
618        fn third_party_api(_rng: &mut impl CryptoRng) -> bool {
619            true
620        }
621
622        fn my_api(rng: &mut (impl TryCryptoRng + ?Sized)) -> bool {
623            let mut infallible_rng = rng.unwrap_mut();
624            third_party_api(&mut infallible_rng)
625        }
626
627        assert!(my_api(&mut SomeRng));
628    }
629
630    #[test]
631    fn reborrow_unwrap_mut() {
632        struct FourRng;
633
634        impl TryRngCore for FourRng {
635            type Error = core::convert::Infallible;
636            fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
637                Ok(4)
638            }
639            fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
640                unimplemented!()
641            }
642            fn try_fill_bytes(&mut self, _: &mut [u8]) -> Result<(), Self::Error> {
643                unimplemented!()
644            }
645        }
646
647        let mut rng = FourRng;
648        let mut rng = rng.unwrap_mut();
649
650        assert_eq!(rng.next_u32(), 4);
651        {
652            let mut rng2 = rng.re();
653            assert_eq!(rng2.next_u32(), 4);
654            // Make sure rng2 is dropped.
655        }
656        assert_eq!(rng.next_u32(), 4);
657    }
658}