Struct rug::rand::RandState

source ·
pub struct RandState<'a> { /* private fields */ }
Expand description

The state of a random number generator.

§Examples

use rug::rand::RandState;
let mut rand = RandState::new();
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);

Implementations§

source§

impl RandState<'_>

source

pub fn new() -> RandState<'static>

Creates a new random generator with a compromise between speed and randomness.

Currently this is equivalent to new_mersenne_twister.

§Examples
use rug::rand::RandState;
let mut rand = RandState::new();
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
source

pub fn new_mersenne_twister() -> RandState<'static>

Creates a random generator with a Mersenne Twister algorithm.

This algorithm is fast and has good randomness properties.

§Examples
use rug::rand::RandState;
let mut rand = RandState::new_mersenne_twister();
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
source

pub fn new_linear_congruential( a: &Integer, c: u32, m: u32 ) -> RandState<'static>

Creates a new random generator with a linear congruential algorithm X = (a × X + c) mod 2m.

The low bits of X in this algorithm are not very random, so only the high half of each X is actually used, that is the higher m/2 bits.

§Examples
use rug::rand::RandState;
use rug::Integer;
let a = match Integer::from_str_radix("292787ebd3329ad7e7575e2fd", 16) {
    Ok(i) => i,
    Err(_) => unreachable!(),
};
let c = 1;
let m = 100;
let mut rand = RandState::new_linear_congruential(&a, c, m);
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
source

pub fn new_linear_congruential_size(size: u32) -> Option<RandState<'static>>

Creates a new random generator with a linear congruential algorithm like the new_linear_congruential method.

For the linear congruential algorithm X = (a × X + c) mod 2m, a, c and m are selected from a table such that at least size bits of each X will be used, that is m/2 ≥ size. The table only has values for size ≤ 128; None will be returned if the requested size is larger.

§Examples
use rug::rand::RandState;
let mut rand = match RandState::new_linear_congruential_size(100) {
    Some(r) => r,
    None => unreachable!(),
};
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
source

pub fn new_custom(custom: &mut dyn RandGen) -> RandState<'_>

Creates a new custom random generator.

If the custom random generator is cloned, the implemented trait method RandGen::boxed_clone is called; this leads to panic if the method returns None.

§Examples
use rug::rand::{RandGen, RandState};
use rug::Integer;
struct Seed;
impl RandGen for Seed {
    fn gen(&mut self) -> u32 {
        // not really random
        0x8CEF_7310
    }
}
let mut seed = Seed;
let mut rand = RandState::new_custom(&mut seed);
let mut i = Integer::from(15);
i.random_below_mut(&mut rand);
println!("0 ≤ {} < 15", i);
assert!(i < 15);
source

pub fn new_custom_boxed(custom: Box<dyn RandGen>) -> RandState<'static>

Creates a new custom random generator.

If the custom random generator is cloned, the implemented trait method RandGen::boxed_clone is called; this leads to panic if the method returns None.

§Examples
use rug::rand::{RandGen, RandState};
use rug::Integer;
struct Seed;
impl RandGen for Seed {
    fn gen(&mut self) -> u32 {
        // not really random
        0x8CEF_7310
    }
}
let seed = Box::new(Seed);
let mut rand = RandState::new_custom_boxed(seed);
let mut i = Integer::from(15);
i.random_below_mut(&mut rand);
println!("0 ≤ {} < 15", i);
assert!(i < 15);
source

pub unsafe fn from_raw(raw: randstate_t) -> RandState<'static>

Creates a random generator from an initialized GMP random generator.

§Safety
  • The value must be initialized as a valid randstate_t.
  • The randstate_t type can be considered as a kind of pointer, so there can be multiple copies of it. Since this function takes over ownership, no other copies of the passed value should exist.
  • The object must be thread safe.
§Examples
use core::mem::MaybeUninit;
use gmp_mpfr_sys::gmp;
use rug::rand::RandState;
let mut rand = unsafe {
    let mut raw = MaybeUninit::uninit();
    gmp::randinit_default(raw.as_mut_ptr());
    let raw = raw.assume_init();
    // raw is initialized and unique
    RandState::from_raw(raw)
};
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
// since rand is a RandState now, deallocation is automatic
source

pub fn into_raw(self) -> randstate_t

Converts a random generator into a GMP random generator.

The returned object should be freed to avoid memory leaks.

§Panics

This method panics if the RandState object was created using new_custom, as the borrow into the custom generator would be terminated once self is consumed. This would lead to undefined behavior if the returned object is used. This method does work with objects created using new_custom_boxed.

§Examples
use gmp_mpfr_sys::gmp;
use rug::rand::RandState;
let rand = RandState::new();
let mut raw = rand.into_raw();
unsafe {
    let u = gmp::urandomb_ui(&mut raw, 32) as u32;
    println!("32 random bits: {:032b}", u);
    // free object to prevent memory leak
    gmp::randclear(&mut raw);
}
source

pub fn as_raw(&self) -> *const randstate_t

Returns a pointer to the inner GMP random generator.

The returned pointer will be valid for as long as self is valid.

§Examples
use rug::rand::RandState;
let mut rand = RandState::new();
let raw_ptr = rand.as_raw();
// There is not much you can do with an immutable randstate_t pointer.
println!("pointer: {:p}", raw_ptr);
let u = rand.bits(32);
println!("32 random bits: {:032b}", u);
source

pub fn as_raw_mut(&mut self) -> *mut randstate_t

Returns an unsafe mutable pointer to the inner GMP random generator.

The returned pointer will be valid for as long as self is valid.

§Examples
use gmp_mpfr_sys::gmp;
use rug::rand::RandState;
let mut rand = RandState::new();
let raw_ptr = rand.as_raw_mut();
unsafe {
    let u1 = gmp::urandomb_ui(raw_ptr, 32) as u32;
    println!("32 random bits: {:032b}", u1);
}
let u2 = rand.bits(32);
println!("another 32 random bits: {:032b}", u2);
source

pub fn into_custom_boxed(self) -> Result<Box<dyn RandGen>, Self>

Converts a random generator into Box<dyn RandGen> if possible.

If the conversion is not possible, Err(self) is returned.

This conversion is always possible when the random generator was created with new_custom_boxed. It is also possible if the generator was cloned, directly or indirectly, from another generator that was created with new_custom or new_custom_boxed.

§Examples
use rug::rand::{RandGen, RandState};
struct Seed;
impl RandGen for Seed {
    fn gen(&mut self) -> u32 {
        // not really random
        0x8CEF_7310
    }
}
let seed = Box::new(Seed);
let rand = RandState::new_custom_boxed(seed);
let mut back_to_seed = rand.into_custom_boxed().unwrap();
assert_eq!(back_to_seed.gen(), 0x8CEF_7310);
source

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

Seeds the random generator.

§Examples
use rug::rand::RandState;
use rug::Integer;
let seed = Integer::from(123456);
let mut rand = RandState::new();
rand.seed(&seed);
let u1a = rand.bits(32);
let u1b = rand.bits(32);
// reseed with the same seed
rand.seed(&seed);
let u2a = rand.bits(32);
let u2b = rand.bits(32);
assert_eq!(u1a, u2a);
assert_eq!(u1b, u2b);
source

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

Generates a random number with the specified number of bits.

§Panics

Panics if bits is greater than 32.

§Examples
use rug::rand::RandState;
let mut rand = RandState::new();
let u = rand.bits(16);
assert!(u < (1 << 16));
println!("16 random bits: {:016b}", u);
source

pub fn below(&mut self, bound: u32) -> u32

Generates a random number below the given boundary value.

This function can never return the maximum 32-bit value; in order to generate a 32-bit random value that covers the whole range, use the bits method with bits set to 32.

§Panics

Panics if the boundary value is zero.

§Examples
use rug::rand::RandState;
let mut rand = RandState::new();
let u = rand.below(10000);
assert!(u < 10000);
println!("0 ≤ {} < 10000", u);

Trait Implementations§

source§

impl Clone for RandState<'_>

source§

fn clone(&self) -> RandState<'static>

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<'a> Debug for RandState<'a>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Default for RandState<'_>

source§

fn default() -> RandState<'static>

Returns the “default value” for a type. Read more
source§

impl Drop for RandState<'_>

source§

fn drop(&mut self)

Executes the destructor for this type. Read more
source§

impl MutRandState for RandState<'_>

source§

impl Send for RandState<'_>

source§

impl Sync for RandState<'_>

Auto Trait Implementations§

§

impl<'a> Freeze for RandState<'a>

§

impl<'a> !RefUnwindSafe for RandState<'a>

§

impl<'a> Unpin for RandState<'a>

§

impl<'a> !UnwindSafe for RandState<'a>

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Az for T

source§

fn az<Dst>(self) -> Dst
where T: Cast<Dst>,

Casts the value.
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<Src, Dst> CastFrom<Src> for Dst
where Src: Cast<Dst>,

source§

fn cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> CheckedAs for T

source§

fn checked_as<Dst>(self) -> Option<Dst>
where T: CheckedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> CheckedCastFrom<Src> for Dst
where Src: CheckedCast<Dst>,

source§

fn checked_cast_from(src: Src) -> Option<Dst>

Casts the value.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> OverflowingAs for T

source§

fn overflowing_as<Dst>(self) -> (Dst, bool)
where T: OverflowingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> OverflowingCastFrom<Src> for Dst
where Src: OverflowingCast<Dst>,

source§

fn overflowing_cast_from(src: Src) -> (Dst, bool)

Casts the value.
source§

impl<T> SaturatingAs for T

source§

fn saturating_as<Dst>(self) -> Dst
where T: SaturatingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> SaturatingCastFrom<Src> for Dst
where Src: SaturatingCast<Dst>,

source§

fn saturating_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> UnwrappedAs for T

source§

fn unwrapped_as<Dst>(self) -> Dst
where T: UnwrappedCast<Dst>,

Casts the value.
source§

impl<Src, Dst> UnwrappedCastFrom<Src> for Dst
where Src: UnwrappedCast<Dst>,

source§

fn unwrapped_cast_from(src: Src) -> Dst

Casts the value.
source§

impl<T> WrappingAs for T

source§

fn wrapping_as<Dst>(self) -> Dst
where T: WrappingCast<Dst>,

Casts the value.
source§

impl<Src, Dst> WrappingCastFrom<Src> for Dst
where Src: WrappingCast<Dst>,

source§

fn wrapping_cast_from(src: Src) -> Dst

Casts the value.