use crate::checksum::char_value;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Blindspot {
Identical,
Caught { delta_mod10: u32 },
Blind { residue: u32 },
NotMrzCharset,
}
impl Blindspot {
pub fn is_blind(self) -> bool {
matches!(self, Self::Blind { .. })
}
}
pub fn blindspot(a: char, b: char) -> Blindspot {
let (va, vb) = match (char_value(a), char_value(b)) {
(Ok(va), Ok(vb)) => (va, vb),
_ => return Blindspot::NotMrzCharset,
};
if a == b {
return Blindspot::Identical;
}
let delta = (va % 10 + 10 - vb % 10) % 10;
if delta == 0 {
Blindspot::Blind { residue: va % 10 }
} else {
Blindspot::Caught { delta_mod10: delta }
}
}
pub const CLASSES: [&[char]; 10] = [
&['0', 'A', 'K', 'U', '<'],
&['1', 'B', 'L', 'V'],
&['2', 'C', 'M', 'W'],
&['3', 'D', 'N', 'X'],
&['4', 'E', 'O', 'Y'],
&['5', 'F', 'P', 'Z'],
&['6', 'G', 'Q'],
&['7', 'H', 'R'],
&['8', 'I', 'S'],
&['9', 'J', 'T'],
];
pub fn class_of(c: char) -> Option<&'static [char]> {
char_value(c).ok().map(|v| CLASSES[(v % 10) as usize])
}
pub fn collisions(c: char) -> Vec<char> {
class_of(c)
.map(|class| class.iter().copied().filter(|&x| x != c).collect())
.unwrap_or_default()
}
#[cfg(test)]
mod tests {
use super::*;
const CHARSET: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<";
#[test]
fn classes_partition_the_alphabet() {
let mut seen: Vec<char> = Vec::new();
for (r, class) in CLASSES.iter().enumerate() {
for &c in *class {
assert_eq!(
char_value(c).unwrap() % 10,
r as u32,
"{c:?} is not in class {r}"
);
assert!(!seen.contains(&c), "{c:?} appears in two classes");
seen.push(c);
}
}
assert_eq!(seen.len(), 37, "the MRZ alphabet has 37 characters");
for c in CHARSET.chars() {
assert!(seen.contains(&c), "{c:?} is in no class");
}
}
#[test]
fn identical_is_never_blind() {
for c in CHARSET.chars() {
assert_eq!(blindspot(c, c), Blindspot::Identical);
assert!(!blindspot(c, c).is_blind());
}
}
#[test]
fn collisions_are_exactly_the_blind_set() {
for c in CHARSET.chars() {
let residue = char_value(c).unwrap() % 10;
let coll = collisions(c);
assert!(!coll.contains(&c));
assert_eq!(coll.len(), CLASSES[residue as usize].len() - 1);
for other in coll {
assert_eq!(blindspot(c, other), Blindspot::Blind { residue });
assert_eq!(blindspot(other, c), Blindspot::Blind { residue });
}
for other in CHARSET
.chars()
.filter(|&x| char_value(x).unwrap() % 10 != residue)
{
assert!(matches!(blindspot(c, other), Blindspot::Caught { .. }));
}
}
}
#[test]
fn non_mrz_characters_are_rejected() {
for c in ['@', 'a', 'é', ' ', '\0'] {
assert_eq!(blindspot(c, 'A'), Blindspot::NotMrzCharset);
assert_eq!(blindspot('A', c), Blindspot::NotMrzCharset);
assert!(collisions(c).is_empty());
assert_eq!(class_of(c), None);
}
}
#[test]
fn class_zero_holds_both_zero_and_filler() {
assert_eq!(CLASSES[0], &['0', 'A', 'K', 'U', '<']);
assert!(blindspot('K', '<').is_blind());
}
}