9
9
10
10
//! [`Rng`] trait
11
11
12
- use rand_core:: { Error , RngCore } ;
13
12
use crate :: distributions:: uniform:: { SampleRange , SampleUniform } ;
14
13
use crate :: distributions:: { self , Distribution , Standard } ;
15
14
use core:: num:: Wrapping ;
16
15
use core:: { mem, slice} ;
16
+ use rand_core:: { Error , RngCore } ;
17
17
18
18
/// An automatically-implemented extension trait on [`RngCore`] providing high-level
19
19
/// generic methods for sampling values and other convenience methods.
@@ -124,10 +124,11 @@ pub trait Rng: RngCore {
124
124
/// ```
125
125
///
126
126
/// [`Uniform`]: distributions::uniform::Uniform
127
+ #[ track_caller]
127
128
fn gen_range < T , R > ( & mut self , range : R ) -> T
128
129
where
129
130
T : SampleUniform ,
130
- R : SampleRange < T >
131
+ R : SampleRange < T > ,
131
132
{
132
133
assert ! ( !range. is_empty( ) , "cannot sample empty range" ) ;
133
134
range. sample_single ( self ) . unwrap ( )
@@ -236,8 +237,9 @@ pub trait Rng: RngCore {
236
237
///
237
238
/// [`fill_bytes`]: RngCore::fill_bytes
238
239
/// [`try_fill`]: Rng::try_fill
240
+ #[ track_caller]
239
241
fn fill < T : Fill + ?Sized > ( & mut self , dest : & mut T ) {
240
- dest. try_fill ( self ) . unwrap_or_else ( |_| panic ! ( "Rng::fill failed" ) )
242
+ dest. try_fill ( self ) . expect ( "Rng::fill failed" )
241
243
}
242
244
243
245
/// Fill any type implementing [`Fill`] with random data
@@ -288,9 +290,12 @@ pub trait Rng: RngCore {
288
290
///
289
291
/// [`Bernoulli`]: distributions::Bernoulli
290
292
#[ inline]
293
+ #[ track_caller]
291
294
fn gen_bool ( & mut self , p : f64 ) -> bool {
292
- let d = distributions:: Bernoulli :: new ( p) . unwrap ( ) ;
293
- self . sample ( d)
295
+ match distributions:: Bernoulli :: new ( p) {
296
+ Ok ( d) => self . sample ( d) ,
297
+ Err ( _) => panic ! ( "p={:?} is outside range [0.0, 1.0]" , p) ,
298
+ }
294
299
}
295
300
296
301
/// Return a bool with a probability of `numerator/denominator` of being
@@ -317,9 +322,15 @@ pub trait Rng: RngCore {
317
322
///
318
323
/// [`Bernoulli`]: distributions::Bernoulli
319
324
#[ inline]
325
+ #[ track_caller]
320
326
fn gen_ratio ( & mut self , numerator : u32 , denominator : u32 ) -> bool {
321
- let d = distributions:: Bernoulli :: from_ratio ( numerator, denominator) . unwrap ( ) ;
322
- self . sample ( d)
327
+ match distributions:: Bernoulli :: from_ratio ( numerator, denominator) {
328
+ Ok ( d) => self . sample ( d) ,
329
+ Err ( _) => panic ! (
330
+ "p={}/{} is outside range [0.0, 1.0]" ,
331
+ numerator, denominator
332
+ ) ,
333
+ }
323
334
}
324
335
325
336
/// Alias for [`Rng::random`].
@@ -432,8 +443,8 @@ where [T]: Fill
432
443
#[ cfg( test) ]
433
444
mod test {
434
445
use super :: * ;
435
- use crate :: test:: rng;
436
446
use crate :: rngs:: mock:: StepRng ;
447
+ use crate :: test:: rng;
437
448
#[ cfg( feature = "alloc" ) ] use alloc:: boxed:: Box ;
438
449
439
450
#[ test]
0 commit comments