File tree Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Expand file tree Collapse file tree 1 file changed +29
-1
lines changed Original file line number Diff line number Diff line change 88
99//! Interface to the random number generator of the operating system.
1010
11- use crate :: { TryCryptoRng , TryRngCore } ;
11+ use crate :: { SeedableRng , TryCryptoRng , TryRngCore } ;
1212
1313/// An interface over the operating-system's random data source
1414///
@@ -109,6 +109,34 @@ impl TryRngCore for OsRng {
109109
110110impl TryCryptoRng for OsRng { }
111111
112+ impl OsRng {
113+ /// Creates a new instance of the RNG `R` seeded via [`OsRng`].
114+ ///
115+ /// This method is the recommended way to construct non-deterministic PRNGs
116+ /// since it is convenient and secure.
117+ ///
118+ /// Note that this method may panic on (extremely unlikely) [`OsRng`] errors.
119+ /// If it's not desirable, use the [`OsRng::try_seed`] method instead.
120+ ///
121+ /// # Panics
122+ ///
123+ /// If [`OsRng`] is unable to provide secure entropy this method will panic.
124+ pub fn seed < R : SeedableRng > ( & mut self ) -> R {
125+ match self . try_seed :: < R > ( ) {
126+ Ok ( res) => res,
127+ Err ( err) => panic ! ( "OsRng::try_seed failed: {}" , err) ,
128+ }
129+ }
130+
131+ /// Creates a new instance of the RNG `R` seeded via [`OsRng`], propagating any errors that may
132+ /// occur.
133+ pub fn try_seed < R : SeedableRng > ( & mut self ) -> Result < R , OsError > {
134+ let mut seed = R :: Seed :: default ( ) ;
135+ self . try_fill_bytes ( seed. as_mut ( ) ) ?;
136+ Ok ( R :: from_seed ( seed) )
137+ }
138+ }
139+
112140#[ test]
113141fn test_os_rng ( ) {
114142 let x = OsRng . try_next_u64 ( ) . unwrap ( ) ;
You can’t perform that action at this time.
0 commit comments