Trait rug::rand::ThreadRandGen

source ·
pub trait ThreadRandGen {
    // Required method
    fn gen(&mut self) -> u32;

    // Provided methods
    fn gen_bits(&mut self, bits: u32) -> u32 { ... }
    fn seed(&mut self, seed: &Integer) { ... }
    fn boxed_clone(&self) -> Option<Box<dyn ThreadRandGen>> { ... }
}
Expand description

Custom random number generator to be used with ThreadRandState.

The methods implemented for this trait, as well as possible destructors, can be used by FFI callback functions. If these methods panic, they can cause the program to abort.

This is similar to RandGen but can only be used in a single thread.

Examples

use rand::rngs::ThreadRng;
use rand::thread_rng;
use rand::RngCore;
use rug::rand::{ThreadRandGen, ThreadRandState};
struct Generator(ThreadRng);
impl ThreadRandGen for Generator {
    fn gen(&mut self) -> u32 {
        self.0.next_u32()
    }
}
let mut rng = Generator(thread_rng());
let mut state = ThreadRandState::new_custom(&mut rng);
let u = state.below(10000);
assert!(u < 10000);
println!("0 ≤ {} < 10000", u);

This would not compile, since ThreadRng is not Send and not Sync.

use rand::rngs::ThreadRng;
use rand::thread_rng;
use rand::RngCore;
use rug::rand::RandGen;
struct Generator(ThreadRng);
impl RandGen for Generator {
    fn gen(&mut self) -> u32 {
        self.0.next_u32()
    }
}

Required Methods§

source

fn gen(&mut self) -> u32

Gets a random 32-bit unsigned integer.

This is similar to RandGen::gen.

Provided Methods§

source

fn gen_bits(&mut self, bits: u32) -> u32

Gets up to 32 random bits.

The default implementation simply calls the gen method once and returns the most significant required bits.

This method can be overridden to store any unused bits for later use. This can be useful for example if the random number generation process is computationally expensive.

This method is similar to RandGen::gen_bits.

source

fn seed(&mut self, seed: &Integer)

Seeds the random number generator.

The default implementation of this function does nothing.

Note that the ThreadRandState::seed method will pass its seed parameter exactly to this function without using it otherwise.

This method is similar to RandGen::seed.

source

fn boxed_clone(&self) -> Option<Box<dyn ThreadRandGen>>

Optionally clones the random number generator.

The default implementation returns None.

This method is similar to RandGen::boxed_clone.

Implementors§