Skip to main content

Random

Struct Random 

Source
#[non_exhaustive]
pub struct Random { /* private fields */ }
Expand description

Random number generator dispatched over RngBackend.

The default backend is Xoshiro256++. Construct with Random::new for entropy-seeded operation under std, or Random::from_seed for a deterministic, allocation-free generator on any target.

§Examples

use vrd::Random;

let mut rng = Random::new();
let n = rng.rand();

Implementations§

Source§

impl Random

Source

pub fn new() -> Self

Creates a new entropy-seeded Xoshiro256++ generator. Requires std for the OS entropy source.

§Examples
use vrd::Random;

let mut rng = Random::new();
Source

pub fn from_seed(seed: [u8; 32]) -> Self

Creates a Xoshiro256++-backed Random from a 32-byte seed. Allocation-free; available on any target.

§Examples
use vrd::Random;

let seed = [0x42; 32];
let mut rng = Random::from_seed(seed);
Source

pub fn from_u64_seed(seed: u64) -> Self

Convenience constructor for a Xoshiro256++-backed instance from a u64 seed. Allocation-free.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(123456789);
Source

pub fn new_mersenne_twister_with_seed(seed: u32) -> Self

Creates a Mersenne-Twister-backed Random seeded with a u32. Requires alloc.

§Examples
use vrd::Random;

let mut rng = Random::new_mersenne_twister_with_seed(42);
Source

pub fn new_pcg32_with_seed(seed: u64) -> Self

Creates a PCG32-backed Random seeded from the given u64. Requires the pcg feature. 16-byte state - the smallest of the family.

§Examples
use vrd::Random;

let mut rng = Random::new_pcg32_with_seed(42);
let _ = rng.rand();
Source

pub fn new_pcg32() -> Self

Creates an entropy-seeded PCG32-backed Random. Requires the pcg feature and std for the OS entropy source.

§Examples
use vrd::Random;

let mut rng = Random::new_pcg32();
let _ = rng.rand();
Source

pub fn new_pcg64_with_seed(seed: u128) -> Self

Creates a PCG64-backed Random seeded from the given u128. Requires the pcg feature. 32-byte state with native 64-bit output.

§Examples
use vrd::Random;

let mut rng = Random::new_pcg64_with_seed(0xCAFE_F00D);
let _ = rng.u64();
Source

pub fn new_pcg64() -> Self

Creates an entropy-seeded PCG64-backed Random. Requires the pcg feature and std for the OS entropy source.

§Examples
use vrd::Random;

let mut rng = Random::new_pcg64();
let _ = rng.u64();
Source

pub fn from_secure_seed(seed: [u8; 32]) -> Self

Creates a ChaCha20-CSPRNG-backed Random from a deterministic 32-byte seed. Requires the crypto feature. Output is bit-for-bit equivalent to rand_chacha::ChaCha20Rng::from_seed(seed).

§Examples
use vrd::Random;

let mut rng = Random::from_secure_seed([42u8; 32]);
let _ = rng.u64();
Source

pub fn new_secure() -> Self

Creates a ChaCha20-CSPRNG-backed Random seeded from the OS entropy source. Requires the crypto feature and std.

§Examples
use vrd::Random;

let mut rng = Random::new_secure();
// crypto-grade UUID v4 / token / etc.
Source

pub fn new_mersenne_twister() -> Self

Creates an entropy-seeded Mersenne-Twister-backed Random. Requires alloc + std.

§Examples
use vrd::Random;

let mut rng = Random::new_mersenne_twister();
Source

pub fn pseudo(&mut self) -> u32

Generates a pseudo-random number by combining multiple random number generations.

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.pseudo();
Source

pub fn rand(&mut self) -> u32

Generates the next u32.

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.rand();
Source

pub fn u64(&mut self) -> u64

Generates the next u64.

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.u64();
Source

pub fn i64(&mut self) -> i64

Generates the next i64.

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.i64();
Source

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

Re-seeds the active backend from a u32.

§Examples
use vrd::Random;

let mut rng = Random::new();
rng.seed(999);
Source

pub fn backend(&self) -> &RngBackend

Returns a reference to the active backend.

§Examples
use vrd::{Random, RngBackend};

let rng = Random::from_u64_seed(42);
match rng.backend() {
    RngBackend::Xoshiro256PlusPlus(_) => println!("Using Xoshiro"),
    _ => unreachable!(),
}
Source

pub fn split(&mut self) -> Option<Random>

Splits this RNG into a second instance whose stream starts 2¹²⁸ calls ahead of self. Both halves remain valid and produce non-overlapping subsequences - safe to hand to two parallel workers without contention.

Available only on the Xoshiro256++ backend (which has the jump operation). Returns None on the Mersenne Twister backend, which has no analogous fixed-distance jump.

Cost: one jump() on self, roughly 256 scalar next_u64 cycles.

§Examples
use vrd::Random;

let mut parent = Random::from_u64_seed(42);
let mut child = parent.split().expect("Xoshiro backend");
// Two independent streams from a single seed.
assert_ne!(parent.u64(), child.u64());
Source

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

Generates an unbiased u32 in [0, range).

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.bounded(10);
assert!(n < 10);
Source

pub fn random_range(&mut self, min: u32, max: u32) -> u32

Generates an unbiased u32 in [min, max).

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.random_range(10, 20);
assert!(n >= 10 && n < 20);
Source

pub fn int(&mut self, min: i32, max: i32) -> i32

Generates an unbiased i32 in [min, max] (inclusive).

§Examples
use vrd::Random;

let mut rng = Random::new();
let n = rng.int(-10, 10);
assert!(n >= -10 && n <= 10);
Source

pub fn range(&mut self, min: i32, max: i32) -> i32

Inclusive alias for Self::int.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let n = rng.range(1, 10);
assert!((1..=10).contains(&n));
Source

pub fn uint(&mut self, min: u32, max: u32) -> u32

Generates an unbiased u32 in [min, max] (inclusive).

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let n = rng.uint(1, 100);
assert!((1..=100).contains(&n));
§Panics

Panics if min > max.

Source

pub fn bool(&mut self, probability: f64) -> bool

Generates a random bool whose probability of true is probability.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let _coin: bool = rng.bool(0.5);
assert!(!rng.bool(0.0));
assert!( rng.bool(1.0));
§Panics

Panics if probability is outside [0.0, 1.0].

Source

pub fn char(&mut self) -> char

Generates a lowercase ASCII character in 'a'..='z'.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let c = rng.char();
assert!(c.is_ascii_lowercase());
Source

pub fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T>

Picks a random reference into values. Returns None if the slice is empty.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let pool = [10, 20, 30, 40, 50];
let pick = rng.choose(&pool).unwrap();
assert!(pool.contains(pick));

let empty: [i32; 0] = [];
assert!(rng.choose(&empty).is_none());
Source

pub fn float(&mut self) -> f32

Generates an f32 in [0.0, 1.0) with full 24-bit mantissa precision.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let x = rng.float();
assert!((0.0..1.0).contains(&x));
Source

pub fn double(&mut self) -> f64

Generates an f64 in [0.0, 1.0) with full 53-bit mantissa precision.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let x = rng.double();
assert!((0.0..1.0).contains(&x));
Source

pub fn f64(&mut self) -> f64

Alias for Self::double.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let x = rng.f64();
assert!((0.0..1.0).contains(&x));
Source

pub fn fill_array<const N: usize>(&mut self) -> [u8; N]

Returns N random bytes on the stack. Allocation-free; works in pure no_std (no alloc feature required).

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let buf: [u8; 32] = rng.fill_array();
assert!(buf.iter().any(|&b| b != 0));
Source

pub fn bytes(&mut self, len: usize) -> Vec<u8>

Returns a fresh Vec<u8> of len random bytes. Requires the alloc feature.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let buf = rng.bytes(16);
assert_eq!(buf.len(), 16);
Source

pub fn string(&mut self, length: usize) -> String

Returns a fresh String of length lowercase ASCII chars. Requires the alloc feature.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let s = rng.string(8);
assert_eq!(s.len(), 8);
assert!(s.chars().all(|c| c.is_ascii_lowercase()));
Source

pub fn iter_u32(&mut self) -> impl Iterator<Item = u32> + '_

Returns an unbounded iterator yielding random u32 values.

The iterator borrows self mutably; collect-into-Vec or .take(n) to bound it.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let xs: Vec<u32> = rng.iter_u32().take(5).collect();
assert_eq!(xs.len(), 5);
Source

pub fn iter_u64(&mut self) -> impl Iterator<Item = u64> + '_

Returns an unbounded iterator yielding random u64 values.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let xs: Vec<u64> = rng.iter_u64().take(5).collect();
assert_eq!(xs.len(), 5);
Source

pub fn iter_bytes(&mut self) -> ByteIter<'_>

Returns an unbounded iterator yielding random bytes.

Internally buffers a u64 per 8 bytes - the same throughput as Self::try_fill_bytes, but ergonomic for take/collect use.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let bytes: Vec<u8> = rng.iter_bytes().take(16).collect();
assert_eq!(bytes.len(), 16);
Source

pub fn uuid_v4_bytes(&mut self) -> [u8; 16]

Generates a random 16-byte buffer formatted as an RFC 4122 version 4 UUID. Allocation-free.

Variant bits and version bits are set per spec; the remaining 122 bits come from the active backend.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let bytes = rng.uuid_v4_bytes();
// Version 4: high nibble of byte 6 is 0x4.
assert_eq!(bytes[6] >> 4, 0x4);
// Variant 10x: high two bits of byte 8 are 0b10.
assert_eq!(bytes[8] >> 6, 0b10);
Source

pub fn uuid_v4(&mut self) -> String

Generates a random RFC 4122 v4 UUID as a hyphenated lowercase String. Requires the alloc feature.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let s = rng.uuid_v4();
assert_eq!(s.len(), 36);
// Hyphens at the canonical 8-4-4-4-12 positions.
assert_eq!(s.as_bytes()[8], b'-');
assert_eq!(s.as_bytes()[13], b'-');
assert_eq!(s.as_bytes()[18], b'-');
assert_eq!(s.as_bytes()[23], b'-');
Source

pub fn hex_token(&mut self, byte_len: usize) -> String

Generates a lowercase hex token of byte_len bytes (so the returned string has length byte_len * 2). Requires alloc.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let token = rng.hex_token(16);
assert_eq!(token.len(), 32);
assert!(token.chars().all(|c| c.is_ascii_hexdigit()));
Source

pub fn base64_token(&mut self, byte_len: usize) -> String

Generates an unpadded URL-safe base64 token of byte_len random bytes. The returned string has length ((byte_len + 2) / 3) * 4, minus padding. Alphabet per RFC 4648 §5: A-Z a-z 0-9 - _. Requires alloc.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let token = rng.base64_token(15);
assert_eq!(token.len(), 20); // 15 bytes -> 20 base64 chars (no padding)
assert!(token.chars().all(|c| matches!(c,
    'A'..='Z' | 'a'..='z' | '0'..='9' | '-' | '_'
)));
Source

pub fn uniform(&mut self, low: f64, high: f64) -> f64

Generates an f64 uniformly distributed in [low, high).

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let x = rng.uniform(-3.0, 3.0);
assert!((-3.0..3.0).contains(&x));
§Panics

Panics if low >= high or if either bound is non-finite.

Source

pub fn shuffle<T>(&mut self, slice: &mut [T])

Fisher-Yates shuffle in place.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let mut deck = [1, 2, 3, 4, 5];
rng.shuffle(&mut deck);
// The shuffled array is a permutation of the original.
let mut sorted = deck;
sorted.sort_unstable();
assert_eq!(sorted, [1, 2, 3, 4, 5]);
Source

pub fn sample<'a, T>(&mut self, slice: &'a [T], amount: usize) -> Vec<&'a T>

Sample amount references without replacement via partial Fisher-Yates with swap_remove - O(amount) draws, each O(1). Requires the alloc feature.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let pool: Vec<u32> = (1..=20).collect();
let picks = rng.sample(&pool, 5);
assert_eq!(picks.len(), 5);
// No duplicates.
let mut as_vals: Vec<u32> = picks.iter().map(|r| **r).collect();
as_vals.sort_unstable();
let mut deduped = as_vals.clone();
deduped.dedup();
assert_eq!(as_vals, deduped);
Source

pub fn sample_with_replacement<'a, T>( &mut self, slice: &'a [T], amount: usize, ) -> Vec<&'a T>

Sample amount references with replacement. Requires the alloc feature.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let pool = ["alpha", "beta", "gamma"];
let picks = rng.sample_with_replacement(&pool, 5);
assert_eq!(picks.len(), 5);
// Every pick is one of the pool entries (duplicates allowed).
for p in picks {
    assert!(pool.contains(p));
}
Source

pub fn rand_slice<'a, T>( &mut self, slice: &'a [T], length: usize, ) -> Result<&'a [T], &'static str>

Returns a contiguous random subslice of length from slice.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let pool = [1, 2, 3, 4, 5, 6, 7, 8];
let window = rng.rand_slice(&pool, 3).unwrap();
assert_eq!(window.len(), 3);
§Errors

Returns Err(&'static str) when:

  • the input slice is empty,
  • length is 0, or
  • length exceeds slice.len().
Source

pub fn normal(&mut self, mu: f64, sigma: f64) -> f64

Standard normal sample, parameterized by (mu, sigma).

Uses the 256-strip Ziggurat method (Marsaglia & Tsang, 2000) with tables generated at build time. The fast path costs one u32 draw, one table lookup, and one f64 multiply; the overhang branch (~1% of calls) adds one exp and one f64 draw; the tail branch (~0.03% of calls) falls back to exponential rejection.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let z = rng.normal(0.0, 1.0);
assert!(z.is_finite());
Source

pub fn exponential(&mut self, rate: f64) -> f64

Exponential sample with the given rate (λ). Mean of the distribution is 1.0 / rate.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let x = rng.exponential(1.5);
assert!(x >= 0.0);
§Panics

Panics if rate <= 0.0.

Source

pub fn poisson(&mut self, mean: f64) -> u64

Poisson sample with the given mean (λ). Uses Knuth’s multiplicative algorithm; cost is O(λ).

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
let k = rng.poisson(3.0);
// k is a non-negative count; with mean 3.0, values cluster
// near 3 but the tail is unbounded.
let _: u64 = k;
Source

pub fn mti(&self) -> usize

Returns the current Mersenne-Twister state index. Returns 0 when the active backend is Xoshiro256++.

§Examples
use vrd::Random;

let rng = Random::from_u64_seed(1);
assert_eq!(rng.mti(), 0); // Xoshiro backend
Source

pub fn set_mti(&mut self, value: usize)

Sets the Mersenne-Twister state index. No-op on the Xoshiro backend.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
rng.set_mti(0); // no-op on Xoshiro; mti() still returns 0
assert_eq!(rng.mti(), 0);
Source

pub fn twist(&mut self)

Forces a Mersenne-Twister state-vector twist. No-op on the Xoshiro backend.

§Examples
use vrd::Random;

let mut rng = Random::from_u64_seed(1);
rng.twist(); // no-op on Xoshiro

Trait Implementations§

Source§

impl Clone for Random

Source§

fn clone(&self) -> Random

Returns a duplicate 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 Debug for Random

Source§

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

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

impl Default for Random

Available on crate feature std only.
Source§

fn default() -> Self

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

impl<'de> Deserialize<'de> for Random

Source§

fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>
where __D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
Source§

impl Display for Random

Source§

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

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

impl PartialEq for Random

Source§

fn eq(&self, other: &Random) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl SeedableRng for Random

Source§

type Seed = [u8; 32]

Seed type, which is restricted to types mutably-dereferenceable as u8 arrays (we recommend [u8; N] for some N). Read more
Source§

fn from_seed(seed: Self::Seed) -> Self

Create a new PRNG using the given seed. Read more
§

fn seed_from_u64(state: u64) -> Self

Create a new PRNG using a u64 seed. Read more
§

fn from_rng<R>(rng: &mut R) -> Self
where R: Rng + ?Sized,

Create a new PRNG seeded from an infallible Rng. Read more
§

fn try_from_rng<R>(rng: &mut R) -> Result<Self, <R as TryRng>::Error>
where R: TryRng + ?Sized,

Create a new PRNG seeded from a potentially fallible Rng. Read more
§

fn fork(&mut self) -> Self
where Self: Rng,

Fork this PRNG Read more
§

fn try_fork(&mut self) -> Result<Self, Self::Error>
where Self: TryRng,

Fork this PRNG Read more
Source§

impl Serialize for Random

Source§

fn serialize<__S>(&self, __serializer: __S) -> Result<__S::Ok, __S::Error>
where __S: Serializer,

Serialize this value into the given Serde serializer. Read more
Source§

impl TryRng for Random

Source§

type Error = Infallible

The type returned in the event of a RNG error. Read more
Source§

fn try_next_u32(&mut self) -> Result<u32, Self::Error>

Return the next random u32.
Source§

fn try_next_u64(&mut self) -> Result<u64, Self::Error>

Return the next random u64.
Source§

fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error>

Fill dst entirely with random data.
Source§

impl StructuralPartialEq for Random

Auto Trait Implementations§

Blanket Implementations§

§

impl<R> TryRngCore for R
where R: TryRng,

§

type Error = <R as TryRng>::Error

👎Deprecated since 0.10.0: use TryRng instead
Error type.
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> 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<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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.

§

impl<R> Rng for R
where R: TryRng<Error = Infallible> + ?Sized,

§

fn next_u32(&mut self) -> u32

Return the next random u32.
§

fn next_u64(&mut self) -> u64

Return the next random u64.
§

fn fill_bytes(&mut self, dst: &mut [u8])

Fill dest with random data. Read more
§

impl<R> RngExt for R
where R: Rng + ?Sized,

§

fn random<T>(&mut self) -> T
where StandardUniform: Distribution<T>,

Return a random value via the StandardUniform distribution. Read more
§

fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>
where Self: Sized, StandardUniform: Distribution<T>,

Return an iterator over random variates Read more
§

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

Generate a random value in the given range. Read more
§

fn random_bool(&mut self, p: f64) -> bool

Return a bool with a probability p of being true. Read more
§

fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool

Return a bool with a probability of numerator/denominator of being true. Read more
§

fn sample<T, D>(&mut self, distr: D) -> T
where D: Distribution<T>,

Sample a new value, using the given distribution. Read more
§

fn sample_iter<T, D>(self, distr: D) -> Iter<D, Self, T>
where D: Distribution<T>, Self: Sized,

Create an iterator that generates values using the given distribution. Read more
§

fn fill<T>(&mut self, dest: &mut [T])
where T: Fill,

Fill any type implementing [Fill] with random data Read more
Source§

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

Source§

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> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

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>,

Source§

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.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

§

impl<R> RngCore for R
where R: Rng,