From b0f4d1927ac0a6bff42bd6e7235e3e821276e032 Mon Sep 17 00:00:00 2001 From: StNicolay Date: Wed, 7 Jun 2023 21:35:22 +0300 Subject: [PATCH] Removed magic values from gen_password. Made generate_password accept constants for the amount the length of the password --- cryptography/src/passwords.rs | 9 +++++---- src/commands/gen_password.rs | 12 ++++++++++-- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/cryptography/src/passwords.rs b/cryptography/src/passwords.rs index de90d41..a93fe1d 100644 --- a/cryptography/src/passwords.rs +++ b/cryptography/src/passwords.rs @@ -16,7 +16,7 @@ bitflags::bitflags! { /// Returns true if the generated master password is valid. /// It checks that it has at least one lowercase, one uppercase, one number and one punctuation char #[inline] -fn check_generated_password(password: &[u8; 32]) -> bool { +fn check_generated_password(password: &[u8; LENGTH]) -> bool { let mut flags = PasswordFlags::empty(); for &byte in password { match byte { @@ -36,12 +36,12 @@ fn check_generated_password(password: &[u8; 32]) -> bool { } #[inline] -fn generate_password(rng: &mut R) -> ArrayString<32> +fn generate_password(rng: &mut R) -> ArrayString where R: Rng + CryptoRng, { loop { - let password: [u8; 32] = array::from_fn(|_| *CHARS.choose(rng).unwrap()); + let password = array::from_fn(|_| *CHARS.choose(rng).unwrap()); if check_generated_password(&password) { return ArrayString::from_byte_string(&password).unwrap(); } @@ -50,7 +50,8 @@ where /// Continuously generates the password until it passes the checks #[inline] -pub fn generate_passwords() -> [ArrayString<32>; 10] { +pub fn generate_passwords( +) -> [ArrayString; AMOUNT] { let mut rng = thread_rng(); array::from_fn(|_| generate_password(&mut rng)) } diff --git a/src/commands/gen_password.rs b/src/commands/gen_password.rs index e26abac..6a6d52e 100644 --- a/src/commands/gen_password.rs +++ b/src/commands/gen_password.rs @@ -5,10 +5,18 @@ use std::fmt::Write; use teloxide::{adaptors::Throttle, prelude::*, types::ParseMode}; use tokio::task::spawn_blocking; +const MESSAGE_HEADER: &str = "Passwords:"; +const PASSWORD_LENGTH: usize = 32; +const PASSWORD_PADDING_LENGTH: usize = 3; +const AMOUNT_OF_PASSWORDS: usize = 10; +type PasswordArray = [ArrayString; AMOUNT_OF_PASSWORDS]; +const BUFFER_LENGTH: usize = + MESSAGE_HEADER.len() + (PASSWORD_LENGTH + PASSWORD_PADDING_LENGTH) * AMOUNT_OF_PASSWORDS; + /// Handles /gen_password command by generating 10 copyable passwords and sending them to the user pub async fn gen_password(bot: Throttle, msg: Message) -> crate::Result<()> { - let mut message: ArrayString<{ 10 + 35 * 10 }> = "Passwords:".try_into().unwrap(); - let passwords = spawn_blocking(generate_passwords).await?; + let mut message: ArrayString = MESSAGE_HEADER.try_into().unwrap(); + let passwords: PasswordArray = spawn_blocking(generate_passwords).await?; for password in passwords { write!(message, "\n`{password}`").unwrap(); }