use subtle::{Choice, ConditionallySelectable, ConstantTimeEq};
#[derive(Clone, Copy, Debug)]
pub struct RecoveryCodes;
impl RecoveryCodes {
#[must_use]
pub fn generate(count: usize) -> Vec<String> {
(0..count).map(|_| Self::code()).collect()
}
pub fn redeem(codes: &mut [String], code: &str) -> bool {
let code = code.trim();
let mut found = Choice::from(0);
let mut matched = 0;
for (index, candidate) in (0u64..).zip(codes.iter()) {
let equal = candidate.as_bytes().ct_eq(code.as_bytes());
matched.conditional_assign(&index, equal);
found |= equal;
}
if !bool::from(found) {
return false;
}
codes[usize::try_from(matched).expect("an index into the codes")] = Self::code();
true
}
fn code() -> String {
format!("{}-{}", laravel::str::random(10), laravel::str::random(10))
}
}