Trait RngExt

Source
pub trait RngExt: Rng {
    // Provided methods
    fn gen_range_checked<T, R>(&mut self, range: R) -> Option<T>
       where T: SampleUniform,
             R: SampleRange<T> { ... }
    fn gen_range_infallible<T>(&mut self, range: RangeToInclusive<T>) -> T
       where T: GenRangeInfallible { ... }
}
Expand description

Extension trait to provide .gen_range_checked()

Provided Methods§

Source

fn gen_range_checked<T, R>(&mut self, range: R) -> Option<T>
where T: SampleUniform, R: SampleRange<T>,

Generate a random value in the given range.

This function is optimised for the case that only a single sample is made from the given range. See also the Uniform distribution type which may be faster if sampling from the same range repeatedly.

If the supplied range is empty, returns None.

(This is a non-panicking version of Rng::gen_range.)

§Example
use tor_basic_utils::RngExt as _;
use tor_error::{Bug, internal};

fn choose(slice: &[i32]) -> Result<i32, Bug> {
    let index = rand::rng()
        .gen_range_checked(0..slice.len())
        .ok_or_else(|| internal!("empty slice"))?;
    Ok(slice[index])
}

assert_eq!(choose(&[42]).unwrap(), 42);
let _: Bug = choose(&[]).unwrap_err();
Source

fn gen_range_infallible<T>(&mut self, range: RangeToInclusive<T>) -> T

Generate a random value in the given upper-bounded-only range.

For use with an inclusive upper-bounded-only range, with types that implement GenRangeInfallible (that necessarily then implement the appropriate rand traits).

This function is optimised for the case that only a single sample is made from the given range. See also the Uniform distribution type which may be faster if sampling from the same range repeatedly.

§Example
use std::time::Duration;
use tor_basic_utils::RngExt as _;

fn stochastic_sleep(max: Duration) {
    let chosen_delay = rand::rng()
        .gen_range_infallible(..=max);
    std::thread::sleep(chosen_delay);
}

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§

Source§

impl<T: Rng> RngExt for T