diff --git a/src/captcha_solutions.rs b/src/captcha_solutions.rs index 2b1ef1f..0594a03 100644 --- a/src/captcha_solutions.rs +++ b/src/captcha_solutions.rs @@ -1,12 +1,22 @@ -use std::sync::{Arc, Mutex, MutexGuard}; +use std::sync::RwLock; struct CaptchaSolutions { last_id: u16, solutions: Vec>, } +impl CaptchaSolutions { + fn get_sol(&self, id: u16) -> &Option { + &self.solutions[id as usize] + } + + fn set_sol(&mut self, id: u16, sol: Option) { + self.solutions[id as usize] = sol; + } +} + pub struct SharedCaptchaSolutions { - arc: Arc>, + inner: RwLock, } impl Default for SharedCaptchaSolutions { @@ -16,42 +26,33 @@ impl Default for SharedCaptchaSolutions { solutions.resize(max_size, None); Self { - arc: Arc::new(Mutex::new(CaptchaSolutions { + inner: RwLock::new(CaptchaSolutions { last_id: 0, solutions, - })), + }), } } } impl SharedCaptchaSolutions { - fn lock(&self) -> MutexGuard { - self.arc.lock().unwrap() - } - - pub fn store_solution(&self, solution: &str) -> u16 { - let mut captcha_solutions = self.lock(); + pub fn store_sol(&self, sol: String) -> u16 { + let mut captcha_solutions = self.inner.write().unwrap(); let new_id = captcha_solutions.last_id.wrapping_add(1); captcha_solutions.last_id = new_id; - captcha_solutions.solutions[new_id as usize] = Some(solution.to_string()); + captcha_solutions.set_sol(new_id, Some(sol)); new_id } pub fn check_answer(&self, id: u16, answer: &str) -> bool { - { - let mut captcha_solutions = self.lock(); - - let id = id as usize; - - if captcha_solutions.solutions[id] == Some(answer.trim().to_string()) { - captcha_solutions.solutions[id] = None; - return true; - } + if *self.inner.read().unwrap().get_sol(id) != Some(answer.trim().to_string()) { + return false; } - false + self.inner.write().unwrap().set_sol(id, None); + + true } } diff --git a/src/routes.rs b/src/routes.rs index f9d150a..9838729 100644 --- a/src/routes.rs +++ b/src/routes.rs @@ -24,6 +24,7 @@ pub async fn index( State(captcha_solutions): State>, ) -> Result { info!("Visited get(index)"); + render_contact_form(IndexParams { config, captcha_solutions, @@ -41,9 +42,9 @@ pub async fn render_contact_form(params: IndexParams<'_>) -> Result