### Test Documentation Examples Source: https://github.com/rust-random/book/blob/master/src/contrib-doc.md Runs all documentation examples as tests to ensure they are correct and up-to-date. ```sh cargo test --doc ``` -------------------------------- ### Install and Build mdBook Source: https://github.com/rust-random/book/blob/master/README.md Installs the mdBook tool and builds the book, opening it in a browser. Ensure you have Cargo installed. ```bash cargo install mdbook --version "^0.4" --force mdbook build --open ``` -------------------------------- ### Run Standard Benchmarks Source: https://github.com/rust-random/book/blob/master/src/contrib-bench.md Execute the standard set of benchmarks for the Rust Random crate. Ensure you have the nightly toolchain installed. ```sh cargo +nightly bench ``` -------------------------------- ### Build and Test the Rust Random Book Source: https://github.com/rust-random/book/blob/master/src/contrib-doc.md Installs mdbook, builds the book, and runs its tests. The --open flag automatically opens the built book in a web browser. ```sh cargo install mdbook --version "^0.4" mdbook build --open mdbook test # To automatically rebuild after any changes: mdbook watch ``` -------------------------------- ### Example of CryptoOperations using SysRng Source: https://github.com/rust-random/book/blob/master/src/guide-test-fn-rng.md Demonstrates the usage of `CryptoOperations` with `SysRng` for cryptographic operations involving random bytes. This code shows how to initialize the struct and call the `xor_with_random_bytes` method. ```rust use rand::{TryCryptoRng, rngs::SysRng}; pub struct CryptoOperations { rng: R } impl CryptoOperations { #[must_use] pub fn new(rng: R) -> Self { Self { rng } } pub fn xor_with_random_bytes(&mut self, secret: &mut [u8; 8]) -> [u8; 8] { let mut mask = [0u8; 8]; self.rng.try_fill_bytes(&mut mask).unwrap(); for (byte, mask_byte) in secret.iter_mut().zip(mask.iter()) { *byte ^= mask_byte; } mask } } fn main() { let rng = SysRng; let mut crypto_ops = ::new(rng); let mut secret: [u8; 8] = *b"\x00\x01\x02\x03\x04\x05\x06\x07"; let mask = crypto_ops.xor_with_random_bytes(&mut secret); println!("Modified Secret (XORed): {:?}", secret); println!("Mask: {:?}", mask); } ``` -------------------------------- ### Deterministic Monte Carlo Simulation with Rayon Source: https://github.com/rust-random/book/blob/master/src/guide-parallel.md This snippet shows a Monte Carlo simulation for approximating Pi. It uses `rayon` for parallel iteration and `ChaCha8Rng` with `set_stream` to ensure each thread gets a unique, deterministic stream of random numbers derived from a single seed. Manual batching is employed to optimize performance by reducing RNG initialization overhead. ```rust use rand::distr::{Distribution, Uniform}; use rand::{SeedableRng, rngs::ChaCha8Rng}; use rayon::prelude::*; static SEED: u64 = 0; static BATCH_SIZE: u64 = 10_000; static BATCHES: u64 = 1000; fn main() { let range = Uniform::new(-1.0f64, 1.0).unwrap(); let in_circle = (0..BATCHES) .into_par_iter() .map(|i| { let mut rng = ChaCha8Rng::seed_from_u64(SEED); rng.set_stream(i); let mut count = 0; for _ in 0..BATCH_SIZE { let a = range.sample(&mut rng); let b = range.sample(&mut rng); if a * a + b * b <= 1.0 { count += 1; } } count }) .reduce(|| 0usize, |a, b| a + b); // prints 3.1409052 (determinstic and reproducible result) println!( "π is approximately {}", 4. * (in_circle as f64) / ((BATCH_SIZE * BATCHES) as f64) ); } ``` -------------------------------- ### Custom Enum Uniform Sampling Source: https://github.com/rust-random/book/blob/master/src/guide-dist.md Implement `Distribution` for `StandardUniform` to sample custom enum variants uniformly. This example shows sampling for a `Food` enum. ```rust use rand::{Rng, RngExt, distr::{Distribution, StandardUniform}}; pub enum Food { Burger, Pizza, Kebab, } impl Distribution for StandardUniform { fn sample(&self, rng: &mut R) -> Food { let index: u8 = rng.random_range(0..3); match index { 0 => Food::Burger, 1 => Food::Pizza, 2 => Food::Kebab, _ => unreachable!(), } } } ``` -------------------------------- ### Getting a Deterministic RNG for Tests Source: https://github.com/rust-random/book/blob/master/src/contrib-test.md Use `::test::rng` to obtain a simple, fast-initializing, and deterministic random number generator for testing purposes when specific RNG properties are not required. The argument is an arbitrary seed value. ```rust let mut rng = ::test::rng(528); // just pick some number ``` -------------------------------- ### Build All API Documentation for Rust Random Crates Source: https://github.com/rust-random/book/blob/master/src/contrib-doc.md Builds API documentation for all crates in the rust-random/rand workspace. Use --no-deps to avoid building dependencies and --all-features to include all features. The RUSTDOCFLAGS environment variable can enable unstable features for better link handling. ```sh # Optionally, enable some unstable but widely used doc features: export RUSTDOCFLAGS="--cfg docsrs -Zunstable-options --generate-link-to-definition" # Build doc for all crates in the workspace: cargo doc --workspace --no-deps --all-features --open ``` -------------------------------- ### Create Symbolic Link for Local API Docs Source: https://github.com/rust-random/book/blob/master/src/contrib-doc.md Creates a symbolic link named 'rand' in the current directory pointing to the local build of the API documentation. This is useful when building the book locally to ensure internal links work correctly. ```sh ln -s ../rand/target/doc rand ``` -------------------------------- ### Testing Rand with Different Environments Source: https://github.com/rust-random/book/blob/master/src/contrib-test.md Run these commands to test the Rand crate in different Rust environments: standard library, core-only, and core+alloc. The core+alloc environment requires a nightly toolchain. ```sh # Test using std: cargo test # Test using only core: cargo test --tests --no-default-features # Test using core + alloc (requires nightly): cargo +nightly test --tests --no-default-features --features=alloc ``` -------------------------------- ### Basic Random Value Generation in Rust Source: https://github.com/rust-random/book/blob/master/src/quick-start.md Demonstrates generating random values of different types (u8, boolean, f64) and using random ranges. It shows how to use the thread-local generator directly for more control. ```rust use rand::prelude::*; fn main() { // We can use random() immediately. It can produce values of many common types: let x: u8 = rand::random(); println!("{}", x); if rand::random() { // generates a boolean println!("Heads!"); } // If we want to be a bit more explicit (and a little more efficient) we can // make a handle to the thread-local generator: let mut rng = rand::rng(); if rng.random() { // random bool let x: f64 = rng.random(); // random number in range [0, 1) let y = rng.random_range(-10.0..10.0); println!("x is: {}", x); println!("y is: {}", y); } println!("Dice roll: {}", rng.random_range(1..=6)); println!("Number from 0 to 9: {}", rng.random_range(0..10)); // Sometimes it's useful to use distributions directly: let distr = rand::distr::Uniform::new_inclusive(1, 100).unwrap(); let mut nums = [0i32; 3]; for x in &mut nums { *x = rng.sample(distr); } println!("Some numbers: {:?}", nums); // We can also interact with iterators and slices: let arrows_iter = "➡⬈⬆⬉⬅⬋⬇⬊".chars(); println!("Lets go in this direction: {}", arrows_iter.choose(&mut rng).unwrap()); let mut nums = [1, 2, 3, 4, 5]; nums.shuffle(&mut rng); println!("I shuffled my {:?}", nums); } ``` -------------------------------- ### Run Benchmarks with Nightly Features Source: https://github.com/rust-random/book/blob/master/src/contrib-bench.md Run benchmarks that may utilize different code paths when specific nightly features are enabled. This command requires the nightly toolchain. ```sh cargo +nightly bench --features=nightly ``` -------------------------------- ### MockCryptoRng for Testing Source: https://github.com/rust-random/book/blob/master/src/guide-test-fn-rng.md A mock RNG implementation for testing purposes, implementing `CryptoRng`, `RngCore`, and `TryCryptoRng`. This allows deterministic testing of functions that rely on random data generation. ```rust #[cfg(test)] mod tests { use super::*; #[derive(Clone, Copy, Debug)] struct MockCryptoRng { data: [u8; 8], index: usize, } impl MockCryptoRng { fn new(data: [u8; 8]) -> MockCryptoRng { MockCryptoRng { data, index: 0, } } } impl CryptoRng for MockCryptoRng {} impl RngCore for MockCryptoRng { fn next_u32(&mut self) -> u32 { unimplemented!() } fn next_u64(&mut self) -> u64 { unimplemented!() } fn fill_bytes(&mut self, dest: &mut [u8]) { for byte in dest.iter_mut() { *byte = self.data[self.index]; self.index = (self.index + 1) % self.data.len(); } } fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), rand::Error> { unimplemented!() } } #[test] fn test_xor_with_mock_rng() { let mock_crypto_rng = MockCryptoRng::new(*b"\x57\x88\x1e\xed\x1c\x72\x01\xd8"); let mut crypto_ops = CryptoOperations::new(mock_crypto_rng); let mut secret: [u8; 8] = *b"\x00\x01\x02\x03\x04\x05\x06\x07"; let mask = crypto_ops.xor_with_random_bytes(&mut secret); let expected_mask = *b"\x57\x88\x1e\xed\x1c\x72\x01\xd8"; let expected_xored_secret = *b"\x57\x89\x1c\xee\x18\x77\x07\xdf"; assert_eq!(secret, expected_xored_secret); assert_eq!(mask, expected_mask); } } ``` -------------------------------- ### Run Rust Project with Randomness Source: https://github.com/rust-random/book/blob/master/src/guide-start.md Execute this command to compile and run your Rust project that uses the 'rand' crate. ```sh $ cargo run Compiling [..] Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.99s Running `target/debug/randomly` Random die roll: 4 Random UUID: 0xEC3936A465339F8295EE11AB853CCDBF You got lucky! ``` -------------------------------- ### Automatic Rebuilds for Documentation on Linux Source: https://github.com/rust-random/book/blob/master/src/contrib-doc.md Continuously rebuilds the documentation whenever files in the src/ or rand_*/ directories are modified on Linux systems using inotifywait. ```sh while inotifywait -r -e close_write src/ rand_*/; do cargo doc; done ``` -------------------------------- ### Run mdBook Tests Workaround Source: https://github.com/rust-random/book/blob/master/README.md Executes a workaround for running mdBook tests by generating test files and then running cargo test. This is used due to limitations in the standard `mdbook test` command. ```bash cd tests ./generate.sh cargo test ``` -------------------------------- ### Testing Rand with All Features Source: https://github.com/rust-random/book/blob/master/src/contrib-test.md This command tests the Rand crate with all available feature flags enabled. Ensure you are in the correct directory for the package you intend to test. ```sh cargo test --all-features ``` -------------------------------- ### Using `rand::rng()` for Non-Deterministic and Deterministic Generators Source: https://github.com/rust-random/book/blob/master/src/guide-gen.md Demonstrates how to obtain a non-deterministic random number generator using `rand::rng()` and a deterministic generator by seeding `rand::rngs::ChaCha8Rng` with a specific value. This is useful for generating random numbers in different scenarios, where reproducibility might be required. ```rust use rand::{RngExt, SeedableRng}; # fn main() { // prepare a non-deterministic random number generator: let mut rng = rand::rng(); println!("{}", rng.random::()); // prints an unknown value // prepare a deterministic generator: let mut rng = rand::rngs::ChaCha8Rng::seed_from_u64(123); println!("{}", rng.random::()); // prints -416273517 # } ``` -------------------------------- ### Seeding RNG from Another RNG using SmallRng::from_rng Source: https://github.com/rust-random/book/blob/master/src/guide-seeding.md A convenience method `SmallRng::from_rng` allows seeding one RNG from another. This is useful for generating initial seeds for reproducible sequences. ```rust use rand::prelude::*; fn main() { let mut rng = SmallRng::from_rng(&mut rand::rng()); println!("{}", rng.random_range(0..100)); } ``` -------------------------------- ### Seeding RNG with Fresh Entropy using rand::make_rng Source: https://github.com/rust-random/book/blob/master/src/guide-seeding.md Use `rand::make_rng()` to obtain an RNG seeded with fresh entropy. This requires the `getrandom` feature to be enabled in `rand_core`. ```rust use rand::prelude::*; use rand::rngs::ChaCha20Rng; fn main() { let mut rng: ChaCha20Rng = rand::make_rng(); println!("{}", rng.random_range(0..100)); } ``` -------------------------------- ### Generate Random Bytes Source: https://github.com/rust-random/book/blob/master/src/guide-data.md Fills a byte array with random data. Ensure you have the `rand` crate imported. ```rust # use rand::Rng; # fn main() { // get some random data: let mut data = [0u8; 8]; rand::rng().fill_bytes(&mut data); println!("{:?}", data) # } ``` -------------------------------- ### Seeded RNG with ChaCha8Rng in Rust Source: https://github.com/rust-random/book/blob/master/src/quick-start.md Demonstrates how to create a reproducible random number generator using a fixed seed with `ChaCha8Rng`. This is useful for testing and simulations where predictable random sequences are needed. ```rust use rand::{rngs::ChaCha8Rng, RngExt, SeedableRng}; fn main() { let mut rng = ChaCha8Rng::seed_from_u64(10); println!("Random f32: {}", rng.random::()); } ``` -------------------------------- ### Add Rand-Distr Crate to Cargo Project Source: https://github.com/rust-random/book/blob/master/src/guide-start.md Use this command to add the 'rand_distr' crate, which provides various probability distributions, to your Rust project. ```sh $ cargo add rand_distr Updating crates.io index Adding rand_distr v0.4.3 to dependencies Features: + alloc + std - serde - serde1 - std_math Updating crates.io index ``` -------------------------------- ### Non-deterministic Multi-threaded RNG Initialization with Rayon Source: https://github.com/rust-random/book/blob/master/src/guide-parallel.md Initializes a new `rand::rng()` in each worker thread using `map_init` for non-deterministic parallel processing. This RNG can be reused across multiple work units. ```rust use rand::distr::{Distribution, Uniform}; use rayon::prelude::*; static SAMPLES: u64 = 1_000_000; fn main() { let range = Uniform::new(-1.0f64, 1.0).unwrap(); let in_circle = (0..SAMPLES) .into_par_iter() .map_init(|| rand::rng(), |rng, _| { let a = range.sample(rng); let b = range.sample(rng); if a * a + b * b <= 1.0 { 1 } else { 0 } }) .reduce(|| 0usize, |a, b| a + b); // prints something close to 3.14159... println!( "π is approximately {}", 4. * (in_circle as f64) / (SAMPLES as f64) ); } ``` -------------------------------- ### Generate Random Boolean using rand::random() Source: https://github.com/rust-random/book/blob/master/src/guide-values.md Shows a shortcut for generating a random boolean value using the `rand::random()` function, which is equivalent to calling `Rng::random()` on the thread-local RNG. ```rust # use rand::Rng; # fn main() { println!("Tossing a coin..."); if rand::random() { println!("We got lucky!"); } # } ``` -------------------------------- ### Seed ChaCha12Rng with SysRng Source: https://github.com/rust-random/book/blob/master/src/guide-rngs.md Explicitly seed a ChaCha12Rng using SysRng for a secure random key. Ensure SysRng is available and trusted. ```rust use rand::{rngs::ChaCha12Rng, rngs::SysRng, SeedableRng}; /// Seed explicitly from SysRng: let mut rng1 = ChaCha12Rng::try_from_rng(&mut SysRng).unwrap(); ``` -------------------------------- ### Seeding RNG from a u64 Number using ChaCha8Rng::seed_from_u64 Source: https://github.com/rust-random/book/blob/master/src/guide-seeding.md Use `SeedableRng::seed_from_u64` to generate a seed from a simple number. This method provides good bit-avalanche for distinct seeds but is not secure for cryptographic purposes. ```rust use rand::prelude::*; use rand::rngs::ChaCha8Rng; fn main() { let mut rng = ChaCha8Rng::seed_from_u64(2); println!("{}", rng.random_range(0..100)); } ``` -------------------------------- ### Generate Random Numbers in Rust Source: https://github.com/rust-random/book/blob/master/src/guide-start.md This Rust code snippet demonstrates how to generate random numbers, including a range, a UUID, and a boolean. ```rust use rand::prelude::*; fn main() { let mut rng = rand::rng(); println!("Random die roll: {}", rng.random_range(1..=6)); println!("Random UUID: 0x{:X}", rng.random::()); if rng.random() { println!("You got lucky!"); } } ``` -------------------------------- ### Seed RNG from String Directly Source: https://github.com/rust-random/book/blob/master/src/guide-seeding.md Use this snippet to quickly seed an RNG with a string. The `rand_seeder` crate handles the hashing and seeding process in one step. ```rust use rand::prelude::*; use rand::rngs::Xoshiro256PlusPlus; use rand_seeder::{Seeder, SipHasher}; fn main() { // In one line: let mut rng: Xoshiro256PlusPlus = Seeder::from("stripy zebra").into_rng(); println!("{}", rng.random::()); // If we want to be more explicit, first we create a SipRng: let hasher = SipHasher::from("a sailboat"); let mut hasher_rng = hasher.into_rng(); // (Note: hasher_rng is a full RNG and can be used directly.) // Now, we use hasher_rng to create a seed: let mut seed: ::Seed = Default::default(); hasher_rng.fill(&mut seed); // And create our RNG from that seed: let mut rng = Xoshiro256PlusPlus::from_seed(seed); println!("{}", rng.random::()); } ``` -------------------------------- ### Reconstructing RNG State Source: https://github.com/rust-random/book/blob/master/src/update-0.10.md Demonstrates how to reconstruct a ChaCha8Rng instance with the same state as another instance, as Clone and serialization traits are no longer implemented. ```rust use rand::{rngs::ChaCha8Rng, Rng, SeedableRng}; let mut rng1: ChaCha8Rng = rand::make_rng(); let _ = rng1.next_u64(); let mut rng2 = ChaCha8Rng::from_seed(rng1.get_seed()); rng2.set_stream(rng1.get_stream()); rng2.set_word_pos(rng1.get_word_pos()); assert_eq!(rng1.next_u64(), rng2.next_u64()); ``` -------------------------------- ### Generate Random Values using Rng trait Source: https://github.com/rust-random/book/blob/master/src/guide-values.md Demonstrates generating an unbiased integer over its entire range, a uniformly distributed float between 0 and 1, and simulating a dice roll using `Rng::random` and `Rng::random_range`. ```rust use rand::RngExt; # fn main() { let mut rng = rand::rng(); // an unbiased integer over the entire range: let i: i32 = rng.random(); println!("i = {i}"); // a uniformly distributed value between 0 and 1: let x: f64 = rng.random(); println!("x = {x}"); // simulate rolling a die: println!("roll = {}", rng.random_range(1..=6)); # } ``` -------------------------------- ### Seeding RNG with a Specific Seed from Another RNG Source: https://github.com/rust-random/book/blob/master/src/guide-seeding.md Explicitly fill a seed array from another RNG and then use it to initialize a specific RNG like `ChaCha8Rng`. This method is recommended for seeding cryptographic PRNGs. ```rust use rand::prelude::*; use rand::rngs::ChaCha8Rng; fn main() { let mut seed: ::Seed = Default::default(); rand::rng().fill(&mut seed); let mut rng = ChaCha8Rng::from_seed(seed); println!("{}", rng.random_range(0..100)); } ``` -------------------------------- ### Add Rand Crate to Cargo Project Source: https://github.com/rust-random/book/blob/master/src/guide-start.md Use this command to add the 'rand' crate to your Rust project's dependencies. ```sh cargo add rand ``` -------------------------------- ### Implement StandardUniform for Custom Angle Type Source: https://github.com/rust-random/book/blob/master/src/guide-values.md This snippet shows how to implement the Distribution trait for a custom Angle struct, enabling it to be sampled using StandardUniform. It uses Uniform::new for precise range sampling. ```rust use rand::{Rng, RngExt}; use rand::distr::{Distribution, StandardUniform, Uniform}; use std::f64::consts::TAU; // = 2π /// Represents an angle, in radians #[derive(Debug)] pub struct Angle(f64); impl Angle { pub fn from_degrees(degrees: f64) -> Self { Angle(degrees * (std::f64::consts::TAU / 360.0)) } } impl Distribution for StandardUniform { fn sample(&self, rng: &mut R) -> Angle { // It would be correct to write: // Angle(rng.random::() * TAU) // However, the following is preferred: Angle(Uniform::new(0.0, TAU).unwrap().sample(rng)) } } fn main() { let angle: Angle = rand::rng().random(); println!("Random angle: {angle:?}"); } ``` -------------------------------- ### Seed ChaCha12Rng with ThreadRng Source: https://github.com/rust-random/book/blob/master/src/guide-rngs.md Seed a ChaCha12Rng using the thread-local RNG. This falls back to SysRng if ThreadRng is not available. ```rust /// Seed from ThreadRng (or SysRng if ThreadRng is not available): let mut rng2: ChaCha12Rng = rand::make_rng(); ``` -------------------------------- ### Distribution Trait Definition Source: https://github.com/rust-random/book/blob/master/src/guide-dist.md Defines the `Distribution` trait for producing random values of type T. It includes the core `sample` method and a convenience `sample_iter` method. ```rust use rand::Rng; // a producer of data of type T: pub trait Distribution { // the key function: fn sample(&self, rng: &mut R) -> T; // a convenience function defined using sample: fn sample_iter(self, rng: R) -> rand::distr::Iter where Self: Sized, R: Rng, { // [has a default implementation] # todo!() } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.