figgyfarts
figgyfarts

Reputation: 174

Rust - Parallel string builder - errors with borrow checker

I have built a password generator whilst learning the basics of the Rust programming language, but I have hit a problem. I cannot seem to parallelise the concatenation of strings in the generate_password function with Rayon. Everytime I try to do this I get errors from the borrow checker. Am I missing something or am I coming about this from the wrong angle? Below is the function without parallelisation so you can see how it should operate when parallelised.

fn generate_password(length: i64) -> String {
    let characters: [char; 91] = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '!', '\'', '$', '%', '^', '&', '*', '(', ')', '-', '_', '=', '+', '[', '{', ']', '}', ';', ':', '"', '@', '#', '~', ',', '<', '.', '>', '/', '?'];

    let mut counter: i64 = 0;
    let mut password: String = String::from("");

    while counter < length {
        let percentage_progress: f64 = ((counter as f64) / (length as f64) * 100.0) + 1.0;
        if percentage_progress % 1.0 == 0.0 {
            println!("{}% complete.", percentage_progress);
        }
        let random_index: usize = rand::thread_rng().gen_range(0..characters.len() - 1);
        password.push(characters[random_index]);
        counter += 1;
    }

    return password;
}

I realise the method of generating the password by storing it all in memory then writing is not the best approach, but I am relatively new to programming as compared to some people on this platform. Any recommendations are greatly appreciated :)

Upvotes: 0

Views: 92

Answers (1)

figgyfarts
figgyfarts

Reputation: 174

I have fixed this code. It turns out VS Code was showing errors that didn't exist after rebooting VS Code. I think the rust analyser stopped working briefly. The code works now :)

Upvotes: 0

Related Questions