RNG backed by a OS-provided random number generation facility
On Linux, this is based on libc::getrandom
, on MacOS it is based on libc::getentropy
.
Usage notes
OsRng
is generally considered to be safe to use for cryptographic purposes. However, since
it results in a syscall for each operation, it may be too slow when used as a general-purpose RNG.
Good choice for seeding other RNGs.
Example
use std::random::OsRng;
let rng = OsRng::new();
println!("{}", rng.next_u64()); // prints a random u64
Run this example
Methods
impl OsRng { ... }
-
fn new() -> OsRng
Create a new instance of OsRng
-
Generate a 32-bit integer.
-
Generate a 64-bit integer.
-
Fill the slice with random bytes.
Mixins
impl OsRng { ... }
-
-
-
Generate a random number in a given integer range.
All range types are supported.
Example
use std::random::thread_rng; let value: i32 = thread_rng().next(0..3); assert!(value >= 0 && value < 3); let value: i32 = thread_rng().next(0..=3); assert!(value >= 0 && value <= 3); let value: i32 = thread_rng().next(..3); assert!(value < 3); let value: i32 = thread_rng().next(..=3); assert!(value <= 3); let value: i32 = thread_rng().next(3..); assert!(value >= 3); let value: i32 = thread_rng().next(..); // Any possible value of i32
Run this example -
fn next_float<T>(rng: &mut Self) -> T
Generate a random floating point number in
[0, 1)
interval.This is equivalent to sampling from StandardFloat distribution.
Example
use std::random::thread_rng; let value: f64 = thread_rng().next_float(); assert!(value >= 0.0 && value < 1.0);
Run this example -
fn shuffle<T>(rng: &mut Self, slice: &mut [T])
Permute a slice of elements in random order.
Example
use std::random::thread_rng; let values = [1, 2, 3, 4, 5]; thread_rng().shuffle(&values); for value in values { println!("{}", value); }
Run this example -
fn choice<T>(rng: &mut Self, slice: &[T]) -> T
Return a random element of the slice.
Example
use std::random::thread_rng; let value = thread_rng().choice(&["hello", "world"]); assert!(value == "hello" || value == "world");
Run this example