#[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
impl Random
Sourcepub fn new() -> Self
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();Sourcepub fn from_u64_seed(seed: u64) -> Self
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);Sourcepub fn new_mersenne_twister_with_seed(seed: u32) -> Self
pub fn new_mersenne_twister_with_seed(seed: u32) -> Self
Sourcepub fn new_pcg32_with_seed(seed: u64) -> Self
pub fn new_pcg32_with_seed(seed: u64) -> Self
Sourcepub fn new_pcg64_with_seed(seed: u128) -> Self
pub fn new_pcg64_with_seed(seed: u128) -> Self
Sourcepub fn from_secure_seed(seed: [u8; 32]) -> Self
pub fn from_secure_seed(seed: [u8; 32]) -> Self
Sourcepub fn new_secure() -> Self
pub fn new_secure() -> Self
Sourcepub fn new_mersenne_twister() -> Self
pub fn new_mersenne_twister() -> Self
Sourcepub fn pseudo(&mut self) -> u32
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();Sourcepub fn seed(&mut self, seed: u32)
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);Sourcepub fn backend(&self) -> &RngBackend
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!(),
}Sourcepub fn split(&mut self) -> Option<Random>
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());Sourcepub fn bounded(&mut self, range: u32) -> u32
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);Sourcepub fn random_range(&mut self, min: u32, max: u32) -> u32
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);Sourcepub fn int(&mut self, min: i32, max: i32) -> i32
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);Sourcepub fn char(&mut self) -> char
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());Sourcepub fn choose<'a, T>(&mut self, values: &'a [T]) -> Option<&'a T>
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());Sourcepub fn float(&mut self) -> f32
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));Sourcepub fn double(&mut self) -> f64
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));Sourcepub fn f64(&mut self) -> f64
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));Sourcepub fn fill_array<const N: usize>(&mut self) -> [u8; N]
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));Sourcepub fn bytes(&mut self, len: usize) -> Vec<u8> ⓘ
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);Sourcepub fn string(&mut self, length: usize) -> String
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()));Sourcepub fn iter_u32(&mut self) -> impl Iterator<Item = u32> + '_
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);Sourcepub fn iter_u64(&mut self) -> impl Iterator<Item = u64> + '_
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);Sourcepub fn iter_bytes(&mut self) -> ByteIter<'_> ⓘ
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);Sourcepub fn uuid_v4_bytes(&mut self) -> [u8; 16]
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);Sourcepub fn uuid_v4(&mut self) -> String
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'-');Sourcepub fn hex_token(&mut self, byte_len: usize) -> String
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()));Sourcepub fn base64_token(&mut self, byte_len: usize) -> String
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' | '-' | '_'
)));Sourcepub fn shuffle<T>(&mut self, slice: &mut [T])
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]);Sourcepub fn sample<'a, T>(&mut self, slice: &'a [T], amount: usize) -> Vec<&'a T>
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);Sourcepub fn sample_with_replacement<'a, T>(
&mut self,
slice: &'a [T],
amount: usize,
) -> Vec<&'a T>
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));
}Sourcepub fn rand_slice<'a, T>(
&mut self,
slice: &'a [T],
length: usize,
) -> Result<&'a [T], &'static str>
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,
lengthis0, orlengthexceedsslice.len().
Sourcepub fn normal(&mut self, mu: f64, sigma: f64) -> f64
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());Sourcepub fn exponential(&mut self, rate: f64) -> f64
pub fn exponential(&mut self, rate: f64) -> f64
Sourcepub fn poisson(&mut self, mean: f64) -> u64
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;Sourcepub fn mti(&self) -> usize
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 backendTrait Implementations§
Source§impl<'de> Deserialize<'de> for Random
impl<'de> Deserialize<'de> for Random
Source§fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
fn deserialize<__D>(__deserializer: __D) -> Result<Self, __D::Error>where
__D: Deserializer<'de>,
Source§impl SeedableRng for Random
impl SeedableRng for Random
Source§type Seed = [u8; 32]
type Seed = [u8; 32]
u8
arrays (we recommend [u8; N] for some N). Read more§fn seed_from_u64(state: u64) -> Self
fn seed_from_u64(state: u64) -> Self
u64 seed. Read more§fn from_rng<R>(rng: &mut R) -> Selfwhere
R: Rng + ?Sized,
fn from_rng<R>(rng: &mut R) -> Selfwhere
R: Rng + ?Sized,
Rng. Read moreSource§impl TryRng for Random
impl TryRng for Random
Source§type Error = Infallible
type Error = Infallible
Source§fn try_next_u32(&mut self) -> Result<u32, Self::Error>
fn try_next_u32(&mut self) -> Result<u32, Self::Error>
u32.Source§fn try_next_u64(&mut self) -> Result<u64, Self::Error>
fn try_next_u64(&mut self) -> Result<u64, Self::Error>
u64.impl StructuralPartialEq for Random
Auto Trait Implementations§
impl Freeze for Random
impl RefUnwindSafe for Random
impl Send for Random
impl Sync for Random
impl Unpin for Random
impl UnsafeUnpin for Random
impl UnwindSafe for Random
Blanket Implementations§
§impl<R> TryRngCore for Rwhere
R: TryRng,
impl<R> TryRngCore for Rwhere
R: TryRng,
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> CloneToUninit for Twhere
T: Clone,
impl<T> CloneToUninit for Twhere
T: Clone,
§impl<R> Rng for Rwhere
R: TryRng<Error = Infallible> + ?Sized,
impl<R> Rng for Rwhere
R: TryRng<Error = Infallible> + ?Sized,
§impl<R> RngExt for Rwhere
R: Rng + ?Sized,
impl<R> RngExt for Rwhere
R: Rng + ?Sized,
§fn random<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
fn random<T>(&mut self) -> Twhere
StandardUniform: Distribution<T>,
StandardUniform distribution. Read more§fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>where
Self: Sized,
StandardUniform: Distribution<T>,
fn random_iter<T>(self) -> Iter<StandardUniform, Self, T>where
Self: Sized,
StandardUniform: Distribution<T>,
§fn random_range<T, R>(&mut self, range: R) -> Twhere
T: SampleUniform,
R: SampleRange<T>,
fn random_range<T, R>(&mut self, range: R) -> Twhere
T: SampleUniform,
R: SampleRange<T>,
§fn random_bool(&mut self, p: f64) -> bool
fn random_bool(&mut self, p: f64) -> bool
p of being true. Read more§fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool
fn random_ratio(&mut self, numerator: u32, denominator: u32) -> bool
numerator/denominator of being
true. Read more