1
1
//! Random value generation.
2
- //!
3
- //! The [`Random`] trait allows generating a random value for a type using a
4
- //! given [`RandomSource`].
2
+
3
+ use crate :: range:: RangeFull ;
5
4
6
5
/// A source of randomness.
7
6
#[ unstable( feature = "random" , issue = "130703" ) ]
@@ -15,39 +14,33 @@ pub trait RandomSource {
15
14
fn fill_bytes ( & mut self , bytes : & mut [ u8 ] ) ;
16
15
}
17
16
18
- /// A trait for getting a random value for a type.
19
- ///
20
- /// **Warning:** Be careful when manipulating random values! The
21
- /// [`random`](Random::random) method on integers samples them with a uniform
22
- /// distribution, so a value of 1 is just as likely as [`i32::MAX`]. By using
23
- /// modulo operations, some of the resulting values can become more likely than
24
- /// others. Use audited crates when in doubt.
17
+ /// A trait representing a distribution of random values for a type.
25
18
#[ unstable( feature = "random" , issue = "130703" ) ]
26
- pub trait Random : Sized {
27
- /// Generates a random value.
28
- fn random ( source : & mut ( impl RandomSource + ?Sized ) ) -> Self ;
19
+ pub trait Distribution < T > {
20
+ /// Samples a random value from the distribution, using the specified random source.
21
+ fn sample ( & self , source : & mut ( impl RandomSource + ?Sized ) ) -> T ;
22
+ }
23
+
24
+ impl < T , DT : Distribution < T > > Distribution < T > for & DT {
25
+ fn sample ( & self , source : & mut ( impl RandomSource + ?Sized ) ) -> T {
26
+ ( * self ) . sample ( source)
27
+ }
29
28
}
30
29
31
- impl Random for bool {
32
- fn random ( source : & mut ( impl RandomSource + ?Sized ) ) -> Self {
33
- u8:: random ( source) & 1 == 1
30
+ impl Distribution < bool > for RangeFull {
31
+ fn sample ( & self , source : & mut ( impl RandomSource + ?Sized ) ) -> bool {
32
+ let byte: u8 = RangeFull . sample ( source) ;
33
+ byte & 1 == 1
34
34
}
35
35
}
36
36
37
37
macro_rules! impl_primitive {
38
38
( $t: ty) => {
39
- impl Random for $t {
40
- /// Generates a random value.
41
- ///
42
- /// **Warning:** Be careful when manipulating the resulting value! This
43
- /// method samples according to a uniform distribution, so a value of 1 is
44
- /// just as likely as [`MAX`](Self::MAX). By using modulo operations, some
45
- /// values can become more likely than others. Use audited crates when in
46
- /// doubt.
47
- fn random( source: & mut ( impl RandomSource + ?Sized ) ) -> Self {
48
- let mut bytes = ( 0 as Self ) . to_ne_bytes( ) ;
39
+ impl Distribution <$t> for RangeFull {
40
+ fn sample( & self , source: & mut ( impl RandomSource + ?Sized ) ) -> $t {
41
+ let mut bytes = ( 0 as $t) . to_ne_bytes( ) ;
49
42
source. fill_bytes( & mut bytes) ;
50
- Self :: from_ne_bytes( bytes)
43
+ <$t> :: from_ne_bytes( bytes)
51
44
}
52
45
}
53
46
} ;
0 commit comments