From 0b92bcd9f3f1bea7ff33796b2648ce55bb237e51 Mon Sep 17 00:00:00 2001 From: StNicolay Date: Fri, 12 May 2023 20:29:44 +0300 Subject: [PATCH] Now creating password on 1 blocking task because the generation doesn't take that long, removed back slash from the password chars --- src/handlers/commands/gen_password.rs | 32 +++++++++++++-------------- 1 file changed, 15 insertions(+), 17 deletions(-) diff --git a/src/handlers/commands/gen_password.rs b/src/handlers/commands/gen_password.rs index 23d9274..63ce89e 100644 --- a/src/handlers/commands/gen_password.rs +++ b/src/handlers/commands/gen_password.rs @@ -1,11 +1,11 @@ use crate::handlers::markups::deletion_markup; use arrayvec::{ArrayString, ArrayVec}; use rand::{rngs::OsRng, seq::SliceRandom}; -use std::{iter, str::from_utf8_unchecked}; +use std::str::from_utf8_unchecked; use teloxide::{adaptors::Throttle, prelude::*, types::ParseMode}; -use tokio::task::JoinSet; +use tokio::task::spawn_blocking; -const CHARS: &[u8] = br##"!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"##; +const CHARS: &[u8] = br##"!"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~"##; /// Returns true if the generated master password is valid. /// It checks that it has at least one lowercase, one lowercase and one punctuation char @@ -28,32 +28,30 @@ fn check_generated_password(password: &[u8]) -> bool { } /// Continuously generates the password until it passes the checks -fn generete_password() -> ArrayString<34> { - loop { - let password: ArrayVec = iter::repeat_with(|| *CHARS.choose(&mut OsRng).unwrap()) - .take(32) +fn generete_passwords() -> ArrayVec, 10> { + let mut passwords = ArrayVec::new_const(); + while !passwords.is_full() { + let password: ArrayVec = (0..32) + .map(|_| *CHARS.choose(&mut OsRng).unwrap()) .collect(); if check_generated_password(&password) { let mut string = ArrayString::<34>::new_const(); string.push('`'); unsafe { string.push_str(from_utf8_unchecked(&password)) }; string.push('`'); - return string; + passwords.push(string) } } + 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::<{ 11 + 35 * 10 }>::new(); - message.push_str("Passwords:\n"); - let mut join_set = JoinSet::new(); - for _ in 0..10 { - join_set.spawn_blocking(generete_password); - } - while let Some(password) = join_set.join_next().await { - message.push_str(password?.as_str()); - message.push('\n') + let mut message: ArrayString<{ 10 + 35 * 10 }> = "Passwords:".try_into().unwrap(); + let passwords = spawn_blocking(|| generete_passwords()).await?; + for password in passwords { + message.push('\n'); + message.push_str(&password) } bot.send_message(msg.chat.id, message.as_str()) .parse_mode(ParseMode::MarkdownV2)