Skip to content

Commit

Permalink
Merge pull request #13 from ideatopia/dev/ludndev
Browse files Browse the repository at this point in the history
use fastrand instead of rand
  • Loading branch information
ludndev authored Jul 17, 2024
2 parents 0220f1d + 6b94a62 commit f035356
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 60 deletions.
49 changes: 1 addition & 48 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ homepage = "https://crates.io/crates/ideatopia-password-generator"
[dependencies]
clap = { version = "4.5.9", features = ["derive"] }
cli-clipboard = "0.4.0"
rand = "0.8.5"
fastrand = "2.1.0"
self_update = "0.41.0"
strum = { version = "0.26", features = ["derive"] }
strum_macros = "0.26.4"
Expand Down
37 changes: 26 additions & 11 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,6 @@ mod test;

use clap::{Parser, ValueEnum};
use cli_clipboard::{ClipboardContext, ClipboardProvider};
use rand::{
seq::{IteratorRandom, SliceRandom},
Rng,
};
use self_update::backends::github::Update;
use std::fs::File;
use std::io::Write;
Expand Down Expand Up @@ -149,7 +145,6 @@ pub fn generate_password(
use_special_chars: bool,
complexity: &ComplexityEnum,
) -> String {
let mut rng = rand::thread_rng();
let (lowercase, uppercase, numbers, special_chars) = (
"abcdefghijklmnopqrstuvwxyz",
"ABCDEFGHIJKLMNOPQRSTUVWXYZ",
Expand All @@ -175,23 +170,43 @@ pub fn generate_password(

if matches!(complexity, ComplexityEnum::Secure | ComplexityEnum::Complex) {
// Select at least one character from each required category for Secure and Complex complexity
password.push(lowercase.chars().choose(&mut rng).unwrap());
password.push(uppercase.chars().choose(&mut rng).unwrap());
password.push(numbers.chars().choose(&mut rng).unwrap());
password.push(
lowercase
.chars()
.nth(fastrand::usize(..lowercase.len()))
.unwrap(),
);
password.push(
uppercase
.chars()
.nth(fastrand::usize(..uppercase.len()))
.unwrap(),
);
password.push(
numbers
.chars()
.nth(fastrand::usize(..numbers.len()))
.unwrap(),
);
}

if use_special_chars {
password.push(special_chars.chars().choose(&mut rng).unwrap());
password.push(
special_chars
.chars()
.nth(fastrand::usize(..special_chars.len()))
.unwrap(),
);
}

// Fill the rest of the password with random characters from the charset
password.extend(
iter::repeat_with(|| charset[rng.gen_range(0..charset.len())])
iter::repeat_with(|| charset[fastrand::usize(..charset.len())])
.take(length - password.len()),
);

// Shuffle the password to ensure randomness
password.shuffle(&mut rng);
fastrand::shuffle(&mut password);

password.iter().collect()
}
Expand Down

0 comments on commit f035356

Please sign in to comment.