Skip to content

Commit ea89918

Browse files
committed
std: add a freestanding random function
1 parent 791244e commit ea89918

File tree

1 file changed

+35
-20
lines changed

1 file changed

+35
-20
lines changed

library/std/src/random.rs

+35-20
Original file line numberDiff line numberDiff line change
@@ -17,26 +17,6 @@ use crate::sys::random as sys;
1717
/// you need a larger quantity of random numbers, consider using another random
1818
/// number generator (potentially seeded from this one).
1919
///
20-
/// # Examples
21-
///
22-
/// Generating a [version 4/variant 1 UUID] represented as text:
23-
/// ```
24-
/// #![feature(random)]
25-
///
26-
/// use std::random::{DefaultRandomSource, Random};
27-
///
28-
/// let bits = u128::random(&mut DefaultRandomSource);
29-
/// let g1 = (bits >> 96) as u32;
30-
/// let g2 = (bits >> 80) as u16;
31-
/// let g3 = (0x4000 | (bits >> 64) & 0x0fff) as u16;
32-
/// let g4 = (0x8000 | (bits >> 48) & 0x3fff) as u16;
33-
/// let g5 = (bits & 0xffffffffffff) as u64;
34-
/// let uuid = format!("{g1:08x}-{g2:04x}-{g3:04x}-{g4:04x}-{g5:012x}");
35-
/// println!("{uuid}");
36-
/// ```
37-
///
38-
/// [version 4/variant 1 UUID]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
39-
///
4020
/// # Underlying sources
4121
///
4222
/// Platform | Source
@@ -89,3 +69,38 @@ impl RandomSource for BestEffortRandomSource {
8969
sys::fill_bytes(bytes, true)
9070
}
9171
}
72+
73+
/// Generates a random value with the default random source.
74+
///
75+
/// This is a convenience function for `T::random(&mut DefaultRandomSource)` and
76+
/// will sample according to the same distribution as the underlying [`Random`]
77+
/// trait implementation.
78+
///
79+
/// **Warning:** Be careful when manipulating random values! The
80+
/// [`random`](Random::random) method on integers samples them with a uniform
81+
/// distribution, so a value of 1 is just as likely as [`i32::MAX`]. By using
82+
/// modulo operations, some of the resulting values can become more likely than
83+
/// others. Use audited crates when in doubt.
84+
///
85+
/// # Examples
86+
///
87+
/// Generating a [version 4/variant 1 UUID] represented as text:
88+
/// ```
89+
/// #![feature(random)]
90+
///
91+
/// use std::random::random;
92+
///
93+
/// let bits = random::<u128>();
94+
/// let g1 = (bits >> 96) as u32;
95+
/// let g2 = (bits >> 80) as u16;
96+
/// let g3 = (0x4000 | (bits >> 64) & 0x0fff) as u16;
97+
/// let g4 = (0x8000 | (bits >> 48) & 0x3fff) as u16;
98+
/// let g5 = (bits & 0xffffffffffff) as u64;
99+
/// let uuid = format!("{g1:08x}-{g2:04x}-{g3:04x}-{g4:04x}-{g5:012x}");
100+
/// println!("{uuid}");
101+
/// ```
102+
///
103+
/// [version 4/variant 1 UUID]: https://en.wikipedia.org/wiki/Universally_unique_identifier#Version_4_(random)
104+
pub fn random<T: Random>() -> T {
105+
T::random(&mut DefaultRandomSource)
106+
}

0 commit comments

Comments
 (0)