fastrand Documentation

repository·master·Indexed 20 days ago

https://github.com/smol-rs/fastrand

A simple and fast random number generator for Rust based on the Wyrand algorithm. It provides a global thread-local generator and local Rng instances for performance, supporting random integer and floating-point generation, collection shuffling, and sampling. Note that fastrand is not cryptographically secure. Version 2.5.0.

Tokens
2.7K
Snippets
15
Records
18
Agent score
68%

What's inside fastrand

  1. Use Rng instances for better performance

    master

    Instead of using the global thread-local generator, you can instantiate a local Rng instance. This is more efficient for high-performance requirements, such as generating large amounts of data in a loop.

    use std::iter::repeat_with;
    
    // Create a new Rng instance
    let mut rng = fastrand::Rng::new();
    
    // Use the instance to generate data efficiently
    let mut bytes: Vec<u8> = repeat_with(|| rng.u8(..)).take(10_000).collect();
  2. Seed the generator for reproducible results

    master

    To ensure the same sequence of random numbers is generated every time the program runs, initialize the global generator with a specific seed using fastrand::seed(n).

    // Pick an arbitrary number as seed.
    fastrand::seed(7);
    
    // Now this prints the same number on every run:
    println!("{}", fastrand::u32(..));
  3. Use fastrand for basic random number generation

    master

    You can use the global thread-local generator provided by fastrand to perform common random operations like flipping booleans, generating integers, or picking elements from a collection.

    Note: The implementation uses Wyrand and is not cryptographically secure.

    // Flip a coin
    if fastrand::bool() {
        println!("heads");
    } else {
        println!("tails");
    }
    
    // Generate a random i32
    let num = fastrand::i32(..);
    
    // Choose a random element in an array
    let v = vec![1, 2, 3, 4, 5];
    let i = fastrand::usize(..v.len());
    let elem = v[i];
  4. Configure fastrand features

    master

    The crate provides the following features:

    • std (enabled by default): Enables the std library. This is required for the global generator and global entropy. Without this feature, Rng can only be instantiated using the with_seed method.
    • js: Assumes that WebAssembly targets are being run in a JavaScript environment.
  5. How WebAssembly (WASM) entropy works in fastrand

    master

    When using WASM targets, the availability of entropy for the global RNG depends on the features enabled:

    1. Standard std targets: Use standard library entropy sources.
    2. WASI WASM: Uses WASI entropy sources.
    3. Non-WASI WASM with js feature: If the js feature is enabled, the crate uses the getrandom crate to access JavaScript environment entropy sources to seed the global RNG.
    4. Non-WASI WASM without js feature: The global RNG will fall back to using a predefined seed, meaning it will not be truly random across different executions.
  6. Use the global thread-local RNG

    master
    The fastrand crate provides a global, thread-local random number generator that can be used without manually managing an Rng instance. This is ideal for simple use cases where you want to generate random values throughout your application. The generator is automatically seeded using system entropy (where available) or a combination of time and thread ID.
  7. Sample multiple values and shuffle collections

    master

    Use choose_multiple to sample $O(n)$ values from a collection or range, and shuffle to reorder a mutable slice in place.

    // Sample values from an array or range with O(n) complexity
    fastrand::choose_multiple([1, 4, 5], 2);
    fastrand::choose_multiple(0..20, 12);
    
    // Shuffle an array
    let mut v = vec![1, 2, 3, 4, 5];
    fastrand::shuffle(&mut v);
  8. Generate random Vecs and Strings

    master

    To generate collections of random data, combine fastrand primitives with std::iter::repeat_with.

    use std::iter::repeat_with;
    
    // Generate a Vec of 10 random i32s
    let v: Vec<i32> = repeat_with(|| fastrand::i32(..)).take(10).collect();
    
    // Generate a String of 10 random alphanumeric characters
    let s: String = repeat_with(fastrand::alphanumeric).take(10).collect();
  9. Generate random integers in a range

    master

    You can generate random values for various integer and floating-point types within a specified range. These functions panic if the provided range is empty.

    Integer types:

    • u8(range), i8(range), u16(range), i16(range), u32(range), i32(range), u64(range), i64(range), u128(range), i128(range), usize(range), isize(range), char(range)

    Floating-point types:

    • f32(): Returns a random f32 in range 0..1.
    • f32_inclusive(): Returns a random f32 in range 0..=1.
    • f64(): Returns a random f64 in range 0..1.
    • f64_inclusive(): Returns a random f64 in range 0..=1.
    let val = fastrand::u32(0..100);
    let f = fastrand::f64();
  10. Pick random elements and shuffle slices

    master

    Use these methods to work with collections:

    • choice(iter): Returns Some(item) from an ExactSizeIterator at random, or None if empty.
    • shuffle(slice): Randomly shuffles the elements of a mutable slice in-place.
    • choose_multiple(source, amount): Collects amount random values from an iterable into a Vec. Complexity is O(n) where n is the length of the iterable. If the source has fewer than amount elements, it returns all available elements.
    let mut rng = fastrand::Rng::new();
    
    // Choose one
    let v = vec![1, 2, 3, 4, 5];
    let choice = rng.choice(v.iter());
    
    // Shuffle
    let mut slice = [1, 2, 3, 4, 5];
    rng.shuffle(&mut slice);
    
    // Multiple
    let multiples = rng.choose_multiple(0..20, 12);
  11. Fork an Rng instance

    master

    The fork() method creates a new Rng instance by deterministically deriving a new seed from the current generator's state. This allows you to create independent 'spinoff' generators that do not produce the same sequence as the parent.

    let mut rng1 = fastrand::Rng::with_seed(0x4d595df4d0f33173);
    let mut rng2 = rng1.fork();
    
    // rng1 and rng2 will now produce different sequences
  12. Generate random characters and strings

    master

    The global RNG provides several functions for generating random characters within specific sets:

    • alphabetic(): Returns a random char in range a-z and A-Z.
    • alphanumeric(): Returns a random char in range a-z, A-Z, and 0-9.
    • lowercase(): Returns a random char in range a-z.
    • uppercase(): Returns a random char in range A-Z.
    • digit(base: u32): Returns a random digit as a char in the given base (0-9 and a-z). Panics if base is 0 or > 36.
    let c = fastrand::alphanumeric();
    let d = fastrand::digit(16); // Hexadecimal digit