### Configure getrandom Opt-in Backends via Cargo.toml Source: https://context7.com/rust-random/getrandom/llms.txt Provides examples of how to configure opt-in backends for the `getrandom` crate using `.cargo/config.toml`. It covers specific backends for Linux (direct syscall, raw asm), x86/x86_64 (RDRAND), AArch64 (RNDR), and Windows (legacy RtlGenRandom). ```toml # .cargo/config.toml # Use direct getrandom syscall on Linux (no /dev/urandom fallback) # Requires Linux kernel 3.17+ or Android API 23+ [target.'cfg(target_os = "linux")'] rustflags = ['--cfg', 'getrandom_backend="linux_getrandom"'] # Use raw asm! syscalls instead of libc on Linux [target.'cfg(target_os = "linux")'] rustflags = ['--cfg', 'getrandom_backend="linux_raw"'] # Use RDRAND instruction on x86/x86_64 [target.'cfg(any(target_arch = "x86_64", target_arch = "x86"))'] rustflags = ['--cfg', 'getrandom_backend="rdrand"'] # Use RNDR register on AArch64 [target.'cfg(target_arch = "aarch64")'] rustflags = ['--cfg', 'getrandom_backend="rndr"'] # Use legacy RtlGenRandom on Windows (for compatibility) [target.'cfg(windows)'] rustflags = ['--cfg', 'getrandom_backend="windows_legacy"'] ``` -------------------------------- ### Enable and use WebAssembly JavaScript backend Source: https://context7.com/rust-random/getrandom/llms.txt Enables the wasm_js feature in Cargo.toml to support Web Crypto API in browsers and Node.js, followed by a Rust implementation example using the fill function. ```toml [dependencies] getrandom = { version = "0.4", features = ["wasm_js"] } ``` ```rust use getrandom::{fill, Error}; fn main() -> Result<(), Error> { let mut buf = [0u8; 32]; fill(&mut buf)?; println!("Random bytes for WebAssembly: {:?}", buf); Ok(()) } ``` -------------------------------- ### Implement Custom Backend in Rust Source: https://github.com/rust-random/getrandom/blob/master/README.md Demonstrates how to provide a custom implementation for fill_uninit using the extern_impl feature and the fill_uninit attribute macro. This requires the nightly-only extern_item_impls feature. ```rust use core::mem::MaybeUninit; #[cfg(getrandom_backend = "extern_impl")] #[getrandom::implementation::fill_uninit] fn my_fill_uninit_implementation( dest: &mut [MaybeUninit] ) -> Result<(), getrandom::Error> { // ... Ok(()) } ``` -------------------------------- ### Handle getrandom Errors in Rust Source: https://context7.com/rust-random/getrandom/llms.txt Demonstrates how to handle errors when generating random data using the `getrandom::fill` function. It shows how to check for OS-specific errors and predefined error constants like `UNSUPPORTED` and `UNEXPECTED`. It also illustrates creating custom errors. ```rust use getrandom::{fill, Error}; fn main() { let mut buf = [0u8; 32]; match fill(&mut buf) { Ok(()) => println!("Successfully generated random bytes"), Err(e) => { // Check if this is an OS-level error if let Some(os_err) = e.raw_os_error() { eprintln!("OS error code: {}", os_err); } // Check for specific error types if e == Error::UNSUPPORTED { eprintln!("This platform is not supported"); } else if e == Error::UNEXPECTED { eprintln!("An unexpected error occurred"); } // Display the error (uses std::io::Error description if std feature enabled) eprintln!("Error: {}", e); eprintln!("Debug: {:?}", e); } } // Create custom errors for application-specific failures let custom_error = Error::new_custom(42); println!("Custom error: {:?}", custom_error); } ``` -------------------------------- ### Implement Custom getrandom Backend in Rust Source: https://context7.com/rust-random/getrandom/llms.txt Explains how to implement a custom random number generator backend for the `getrandom` crate by enabling the `custom` backend and defining an `extern "Rust"` function. This is useful for unsupported platforms or custom entropy sources. ```rust // In your Cargo.toml or .cargo/config.toml: // [target.'cfg(...)'] // rustflags = ['--cfg', 'getrandom_backend="custom"'] use getrandom::Error; // Define the custom implementation in your root crate (e.g., main.rs) #[unsafe(no_mangle)] unsafe extern "Rust" fn __getrandom_v03_custom( dest: *mut u8, len: usize, ) -> Result<(), Error> { // Example: Fill buffer with data from a hardware RNG let buf = unsafe { // Initialize buffer to zeros first core::ptr::write_bytes(dest, 0, len); // Create a mutable slice core::slice::from_raw_parts_mut(dest, len) }; // Your custom entropy source implementation here // This example uses a placeholder - replace with actual entropy source for (i, byte) in buf.iter_mut().enumerate() { *byte = (i as u8).wrapping_mul(17).wrapping_add(42); } Ok(()) } fn main() -> Result<(), Error> { let mut buf = [0u8; 16]; getrandom::fill(&mut buf)?; println!("Custom random bytes: {:?}", buf); Ok(()) } ``` -------------------------------- ### Function: fill_uninit Source: https://context7.com/rust-random/getrandom/llms.txt Fills a potentially uninitialized buffer with random bytes, returning a mutable reference to the initialized data. ```APIDOC ## FUNCTION fill_uninit ### Description Fills a potentially uninitialized buffer with random bytes and returns a mutable reference to the initialized bytes, avoiding unnecessary zero-initialization. ### Method Rust Function Call ### Parameters #### Request Body - **dest** (&mut [MaybeUninit]) - Required - The uninitialized buffer to fill. ### Request Example ```rust let mut buf: [MaybeUninit; 64] = [MaybeUninit::uninit(); 64]; let initialized = fill_uninit(&mut buf)?; ``` ### Response #### Success Response (Ok(&mut [u8])) - **Result** (Result<&mut [u8], Error>) - Returns a mutable slice of initialized bytes on success. #### Response Example ```rust Ok(&[0xAF, 0x3B, ...]) ``` ``` -------------------------------- ### Configure getrandom for WebAssembly targets Source: https://context7.com/rust-random/getrandom/llms.txt Configures the getrandom crate to use an unsupported backend for wasm32 targets or sets a specific backend via environment variables. ```toml [target.'cfg(target_arch = "wasm32")'] rustflags = ['--cfg', 'getrandom_backend="unsupported"'] ``` ```bash RUSTFLAGS='--cfg getrandom_backend="linux_getrandom"' cargo build ``` -------------------------------- ### Infallible Random Number Generation with SysRng in Rust Source: https://context7.com/rust-random/getrandom/llms.txt Demonstrates how to use `SysRng` with `UnwrapErr` to provide an infallible random number generator interface in Rust. This approach panics if an error occurs during random number generation, simplifying usage when errors are not expected or handled. ```rust // Using SysRng as an infallible Rng with UnwrapErr use getrandom::rand_core::{Rng, UnwrapErr}; use getrandom::SysRng; fn main() { // Wrap in UnwrapErr for infallible interface (panics on error) let mut rng = UnwrapErr(SysRng); // Now you can use standard Rng methods let random_u64: u64 = rng.next_u64(); let random_u32: u32 = rng.next_u32(); println!("Random u64: {}", random_u64); println!("Random u32: {}", random_u32); } ``` -------------------------------- ### Configure getrandom backend via Environment Variable Source: https://github.com/rust-random/getrandom/blob/master/README.md Sets the getrandom_backend configuration flag using the RUSTFLAGS environment variable during the build process. ```shell RUSTFLAGS='--cfg getrandom_backend="linux_getrandom"' cargo build ``` -------------------------------- ### Use SysRng for Cryptographically Secure Randomness in Rust Source: https://context7.com/rust-random/getrandom/llms.txt Shows how to use `SysRng`, a `rand_core` compatible RNG provided by the `getrandom` crate, for cryptographically secure random number generation. This requires enabling the `sys_rng` feature. It demonstrates using the `TryRng` trait to fill byte arrays. ```rust // Requires the `sys_rng` feature in Cargo.toml: // getrandom = { version = "0.4", features = ["sys_rng"] } use getrandom::{rand_core::TryRng, SysRng}; fn main() -> Result<(), getrandom::Error> { // SysRng is zero-sized and can be constructed directly let mut rng = SysRng; // Use TryRng trait methods let mut key = [0u8; 32]; rng.try_fill_bytes(&mut key)?; println!("Generated key: {:?}", key); Ok(()) } ``` -------------------------------- ### Configure getrandom backend via Cargo Source: https://github.com/rust-random/getrandom/blob/master/README.md Sets the getrandom_backend configuration flag for specific target operating systems within the .cargo/config.toml file. ```toml [target.'cfg(target_os = "linux")'] rustflags = ['--cfg', 'getrandom_backend="linux_getrandom"'] ``` -------------------------------- ### Function: fill Source: https://context7.com/rust-random/getrandom/llms.txt Fills a mutable byte slice with cryptographically secure random bytes. This is the primary method for populating buffers with entropy. ```APIDOC ## FUNCTION fill ### Description Fills a mutable byte slice with cryptographically secure random bytes from the system's preferred random number source. Returns an error on any failure. ### Method Rust Function Call ### Parameters #### Request Body - **dest** (&mut [u8]) - Required - A mutable slice to be filled with random bytes. ### Request Example ```rust let mut buffer = [0u8; 32]; fill(&mut buffer)?; ``` ### Response #### Success Response (Ok(())) - **Result** (Result<(), Error>) - Returns Ok(()) on success, or an Error if the system source fails. #### Response Example ```rust Ok(()) ``` ``` -------------------------------- ### Function: u32 / u64 Source: https://context7.com/rust-random/getrandom/llms.txt Generates a single random integer of the specified bit-width directly from the system source. ```APIDOC ## FUNCTION u32 / u64 ### Description Retrieves a single random u32 or u64 value. Optimized for generating individual random integers. ### Method Rust Function Call ### Parameters None ### Request Example ```rust let val = u32()?; let val64 = u64()?; ``` ### Response #### Success Response (Ok(T)) - **Result** (Result or Result) - The generated random integer. #### Response Example ```rust Ok(123456789) ``` ``` -------------------------------- ### Implement custom getrandom backend Source: https://github.com/rust-random/getrandom/blob/master/README.md Defines the required extern function to provide a custom entropy source for the getrandom crate. The implementation must be defined once and handle raw pointers to fill buffers with random data. ```rust use getrandom::Error; #[unsafe(no_mangle)] unsafe extern "Rust" fn __getrandom_v03_custom( dest: *mut u8, len: usize, ) -> Result<(), Error> { todo!() } ``` ```rust use getrandom::Error; fn my_entropy_source(buf: &mut [u8]) -> Result<(), getrandom::Error> { // ... Ok(()) } #[unsafe(no_mangle)] unsafe extern "Rust" fn __getrandom_v03_custom( dest: *mut u8, len: usize, ) -> Result<(), Error> { let buf = unsafe { // fill the buffer with zeros core::ptr::write_bytes(dest, 0, len); // create mutable byte slice core::slice::from_raw_parts_mut(dest, len) }; my_entropy_source(buf) } ``` -------------------------------- ### Fill Uninitialized Buffer with Random Bytes (Rust) Source: https://context7.com/rust-random/getrandom/llms.txt Fills a potentially uninitialized buffer with random bytes and returns a mutable reference to the initialized bytes. This function is useful for avoiding unnecessary zero-initialization when the buffer will be immediately overwritten with random data. It guarantees that on success, the entire destination buffer is initialized. ```rust use core::mem::MaybeUninit; use getrandom::{fill_uninit, Error}; fn main() -> Result<(), Error> { // Create an uninitialized buffer - avoids the cost of zero-initialization let mut buf: [MaybeUninit; 64] = [MaybeUninit::uninit(); 64]; // Fill with random data and get back an initialized slice let initialized: &mut [u8] = fill_uninit(&mut buf)?; // The returned slice has the same length as the input assert_eq!(initialized.len(), 64); println!("Random bytes: {:?}", initialized); // Useful for generating cryptographic material without extra allocations let mut key_material: [MaybeUninit; 32] = [MaybeUninit::uninit(); 32]; let key = fill_uninit(&mut key_material)?; println!("Key material: {:?}", key); Ok(()) } ``` -------------------------------- ### Fill Buffer with Random Bytes (Rust) Source: https://context7.com/rust-random/getrandom/llms.txt Fills a mutable byte slice with cryptographically secure random bytes from the system's preferred random number source. It returns an error on any failure and handles empty buffers efficiently by avoiding system calls. This is a low-level building block for generating random data. ```rust use getrandom::{fill, Error}; fn main() -> Result<(), Error> { // Generate 32 random bytes for a cryptographic key let mut key = [0u8; 32]; fill(&mut key)?; println!("Generated key: {:?}", key); // Generate a random initialization vector let mut iv = [0u8; 16]; fill(&mut iv)?; println!("Generated IV: {:?}", iv); // Generate larger amounts of random data let mut large_buffer = vec![0u8; 1024]; fill(&mut large_buffer)?; println!("Generated {} random bytes", large_buffer.len()); // Empty slices are handled efficiently (no system calls) fill(&mut [])?; Ok(()) } ``` -------------------------------- ### Generate Random u64 Value (Rust) Source: https://context7.com/rust-random/getrandom/llms.txt Retrieves a single random u64 value from the system's preferred random number source. This is useful for generating unique identifiers, seeds for PRNGs, or any situation requiring 64 bits of randomness. It can also be combined to generate larger random values. ```rust use getrandom::{u64, Error}; fn main() -> Result<(), Error> { // Generate a random u64 for a unique identifier let unique_id = u64()?; println!("Unique ID: {}", unique_id); // Generate a seed for a random number generator let rng_seed = u64()?; println!("RNG seed: 0x{:016x}", rng_seed); // Combine two u64 values for a 128-bit value let high = u64()?; let low = u64()?; let uuid_like = ((high as u128) << 64) | (low as u128); println!("128-bit random: 0x{:032x}", uuid_like); Ok(()) } ``` -------------------------------- ### Generate random u128 using getrandom in Rust Source: https://github.com/rust-random/getrandom/blob/master/README.md This function demonstrates how to fill a byte buffer with cryptographically secure random data provided by the operating system and convert it into a u128 integer. It returns a Result type to handle potential errors during the entropy retrieval process. ```rust fn get_random_u128() -> Result { let mut buf = [0u8; 16]; getrandom::fill(&mut buf)?; Ok(u128::from_ne_bytes(buf)) } ``` -------------------------------- ### Generate Random u32 Value (Rust) Source: https://context7.com/rust-random/getrandom/llms.txt Retrieves a single random u32 value from the system's preferred random number source. This function is optimized for generating individual random integers and may be more efficient than calling `fill` for small amounts of data on some platforms. It's useful for seeding PRNGs or generating random game mechanics. ```rust use getrandom::{u32, Error}; fn main() -> Result<(), Error> { // Generate a random u32 for seeding a fast PRNG let seed = u32()?; println!("Random seed: {}", seed); // Generate random values for game mechanics let dice_roll = (u32()? % 6) + 1; println!("Dice roll: {}", dice_roll); // Generate multiple random u32 values let random_values: Vec = (0..10) .map(|_| u32()) .collect::, _>>()?; println!("Random u32 values: {:?}", random_values); Ok(()) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.