How to Generator Simple Auth Token in Rust

In Rust, you can use the functionality provided by the rand crate to generate secure random numbers. Here is an example of a Rust function that emulates the functionality of the JavaScript function you provided:

First, make sure that your Cargo.toml file includes the rand crate:

[dependencies]
rand = "0.8.5"

Then, you can write the following Rust code:

use rand::{distributions::Alphanumeric, Rng, CryptoRng};

fn generate_token(length: usize, options: Option<(bool, bool, bool)>) -> Result<String, &'static str> {
    let (uppercase, lowercase, numbers) = match options {
        Some((uppercase, lowercase, numbers)) => (uppercase, lowercase, numbers),
        None => (true, true, true),
    };

    let mut charset = String::new();
    if uppercase {
        charset += "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    if lowercase {
        charset += "abcdefghijklmnopqrstuvwxyz";
    }
    if numbers {
        charset += "0123456789";
    }

    if charset.is_empty() {
        return Err("At least one character set must be selected.");
    }

    let mut rng = rand::thread_rng();
    let token: String = (0..length)
        .map(|_| {
            let idx = rng.gen_range(0..charset.len());
            charset.chars().nth(idx).unwrap()
        })
        .collect();

    Ok(token)
}

fn main() {
    match generate_token(16, Some((true, true, true))) {
        Ok(token) => println!("Generated token: {}", token),
        Err(e) => println!("Error: {}", e),
    }
}

In this Rust function, generate_token accepts two parameters: length (the length of the token) and an Option containing a tuple of three boolean values, which include configurations for whether to include uppercase letters, lowercase letters, and numbers. Inside the function, a character set charset is constructed, and then rand::thread_rng is used to create a random number generator for the current thread. For each character of the token, a random index is generated and used to select a character from charset.

Please note that the rand crate provides various random number generators, among which the CryptoRng trait represents cryptographically secure random number generators. In this example, we use rand::thread_rng, which returns a random number generator that implements CryptoRng.

In the main function, we provide an example usage and print the generated token. If no character set is provided in options, the function will return an error. You can adjust the parameters of the generate_token function to generate tokens of different lengths and character sets as needed.