contact-form/src/captcha_solutions.rs
2022-10-29 00:40:54 +02:00

55 lines
1.3 KiB
Rust

use std::sync::{Arc, Mutex, MutexGuard};
struct CaptchaSolutions {
last_id: u16,
solutions: Vec<Option<String>>,
}
pub struct SharedCaptchaSolutions {
arc: Arc<Mutex<CaptchaSolutions>>,
}
impl SharedCaptchaSolutions {
pub fn new() -> Self {
let max_size = (u16::MAX as usize) + 1;
let mut solutions = Vec::with_capacity(max_size);
solutions.resize(max_size, None);
Self {
arc: Arc::new(Mutex::new(CaptchaSolutions {
last_id: 0,
solutions,
})),
}
}
fn lock(&self) -> MutexGuard<CaptchaSolutions> {
self.arc.lock().unwrap()
}
pub fn store_solution(&self, solution: &str) -> u16 {
let mut captcha_solutions = self.lock();
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());
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;
}
}
false
}
}