contact-form/src/captcha_solutions.rs

56 lines
1.3 KiB
Rust
Raw Normal View History

2022-10-28 22:40:54 +00:00
use std::sync::{Arc, Mutex, MutexGuard};
2022-10-26 00:23:55 +00:00
2022-10-28 22:40:54 +00:00
struct CaptchaSolutions {
2022-10-26 00:23:55 +00:00
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,
})),
}
}
2022-10-28 22:40:54 +00:00
fn lock(&self) -> MutexGuard<CaptchaSolutions> {
self.arc.lock().unwrap()
}
2022-10-26 00:23:55 +00:00
pub fn store_solution(&self, solution: &str) -> u16 {
2022-10-28 22:40:54 +00:00
let mut captcha_solutions = self.lock();
2022-10-26 00:23:55 +00:00
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 {
2022-10-27 16:44:40 +00:00
{
2022-10-28 22:40:54 +00:00
let mut captcha_solutions = self.lock();
2022-10-26 00:23:55 +00:00
2022-10-27 16:44:40 +00:00
let id = id as usize;
2022-10-26 00:23:55 +00:00
2022-10-27 16:44:40 +00:00
if captcha_solutions.solutions[id] == Some(answer.trim().to_string()) {
captcha_solutions.solutions[id] = None;
return true;
}
2022-10-26 00:23:55 +00:00
}
false
}
}