use std::collections::BTreeSet;
use crate::checksum::{is_mrz_charset, normalize_line};
use crate::parser::{
candidate_lines, parse_mrv_a_with, parse_mrv_b_with, parse_td2_with, parse_td3_with,
};
use crate::rank::{flag_reason, FlagReason};
use crate::{Format, MrzData, MrzError, ParseOptions};
const NAME_FIELD_START: usize = 5;
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Line1Selection {
pub verdict: Line1Verdict,
pub eligible: usize,
pub distinct: usize,
}
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line1Verdict {
OutOfScope,
Kept,
Unresolved(Line1Unresolved),
NoCandidate,
Ambiguous,
Proposed(MrzData),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Line1Unresolved {
IssuerUnresolved,
RepeatedLine,
DigitInNameField,
}
fn unresolved_from(reason: FlagReason) -> Line1Unresolved {
match reason {
FlagReason::IssuerUnresolved => Line1Unresolved::IssuerUnresolved,
FlagReason::RepeatedLine => Line1Unresolved::RepeatedLine,
FlagReason::DigitInNameField => Line1Unresolved::DigitInNameField,
}
}
pub fn select_line1(text: &str, accepted: &MrzData, opts: &ParseOptions) -> Line1Selection {
let done = |verdict| Line1Selection {
verdict,
eligible: 0,
distinct: 0,
};
let width = match line1_width(accepted.format) {
Some(width) if accepted.valid() => width,
_ => return done(Line1Verdict::OutOfScope),
};
let mut zone_lines = accepted.mrz_lines.lines();
let (Some(incumbent_line1), Some(accepted_line2), None) =
(zone_lines.next(), zone_lines.next(), zone_lines.next())
else {
return done(Line1Verdict::OutOfScope);
};
if incumbent_line1.len() != width || accepted_line2.len() != width {
return done(Line1Verdict::OutOfScope);
}
let (Some(incumbent_prefix), Some(incumbent_field)) = (
incumbent_line1.get(..NAME_FIELD_START),
incumbent_line1.get(NAME_FIELD_START..),
) else {
return done(Line1Verdict::OutOfScope);
};
if name_field_is_grammatical(incumbent_field) {
return done(Line1Verdict::Kept);
}
if let Some(reason) = flag_reason(accepted) {
return done(Line1Verdict::Unresolved(unresolved_from(reason)));
}
let candidates: Vec<String> = candidate_lines(text)
.iter()
.map(|line| normalize_line(line))
.collect();
let mut eligible = 0;
let mut distinct_fields: BTreeSet<&str> = BTreeSet::new();
let mut proposals: Vec<MrzData> = Vec::new();
for candidate in &candidates {
let Some(proposal) = eligible_proposal(
candidate,
width,
incumbent_prefix,
accepted_line2,
accepted,
opts,
) else {
continue;
};
eligible += 1;
let field = candidate.get(NAME_FIELD_START..).unwrap_or("");
if distinct_fields.insert(field) {
proposals.push(proposal);
}
}
let distinct = distinct_fields.len();
let verdict = match proposals.len() {
0 => Line1Verdict::NoCandidate,
1 => match proposals.pop() {
Some(proposal) => Line1Verdict::Proposed(proposal),
None => Line1Verdict::NoCandidate,
},
_ => Line1Verdict::Ambiguous,
};
Line1Selection {
verdict,
eligible,
distinct,
}
}
fn line1_width(format: Format) -> Option<usize> {
match format {
Format::Td3 | Format::MrvA => Some(44),
Format::Td2 | Format::MrvB => Some(36),
Format::Td1 => None,
}
}
fn eligible_proposal(
candidate: &str,
width: usize,
incumbent_prefix: &str,
accepted_line2: &str,
accepted: &MrzData,
opts: &ParseOptions,
) -> Option<MrzData> {
if !is_mrz_charset(candidate) || candidate.len() != width {
return None;
}
if candidate.get(..NAME_FIELD_START)? != incumbent_prefix {
return None;
}
if !name_field_is_grammatical(candidate.get(NAME_FIELD_START..)?) {
return None;
}
let parsed: Result<MrzData, MrzError> = match accepted.format {
Format::Td3 => parse_td3_with(candidate, accepted_line2, opts),
Format::Td2 => parse_td2_with(candidate, accepted_line2, opts),
Format::MrvA => parse_mrv_a_with(candidate, accepted_line2, opts),
Format::MrvB => parse_mrv_b_with(candidate, accepted_line2, opts),
Format::Td1 => return None,
};
let mut proposal = parsed.ok()?;
if !proposal.valid() {
return None;
}
proposal.damaged_recovery = accepted.damaged_recovery;
if !differs_in_names_only(&proposal, accepted) {
return None;
}
Some(proposal)
}
fn differs_in_names_only(proposal: &MrzData, accepted: &MrzData) -> bool {
let mut probe = proposal.clone();
probe.surname = accepted.surname.clone();
probe.given_names = accepted.given_names.clone();
let line1_of_accepted = accepted.mrz_lines.lines().next().unwrap_or("");
let line2_of_proposal = proposal.mrz_lines.lines().nth(1).unwrap_or("");
probe.mrz_lines = format!("{line1_of_accepted}\n{line2_of_proposal}");
probe == *accepted
}
fn name_field_is_grammatical(field: &str) -> bool {
let bytes = field.trim_end_matches('<').as_bytes();
let mut at = 0;
let mut seen_double = false;
loop {
let letters_start = at;
while at < bytes.len() && bytes[at].is_ascii_uppercase() {
at += 1;
}
if at == letters_start {
return false;
}
if at == bytes.len() {
return true;
}
let filler_start = at;
while at < bytes.len() && bytes[at] == b'<' {
at += 1;
}
match at - filler_start {
1 => {}
2 if !seen_double => seen_double = true,
_ => return false,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn grammatical_name_fields() {
for field in [
"SPECIMEN<<TEST<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<",
"SPECIMEN<<TEST<ANNA<<<<<<<<",
"DE<LA<CRUZ<<MARIA<<<<<<<<<<",
"SPECIMEN<<<<<<<<<<<<<<<<<<<",
"HASSAN<FARID<RAGUE<<<<<<<<<",
"A",
] {
assert!(name_field_is_grammatical(field), "{field}");
}
}
#[test]
fn ungrammatical_name_fields() {
for (field, why) in [
("", "empty"),
("<<<<<<<<<<", "all filler"),
("<SPECIMEN<<TEST", "leading filler"),
("SPECIMEN<<<TEST", "a <<< run inside"),
(
"IBRAHIM<<ABDIAZIZ<MOHAMUD<<<<<<Z",
"a <<< run, then a letter",
),
("SPECIMEN<<TEST<<ANNA", "a second <<"),
("SPEC1MEN<<TEST", "a digit"),
("SPECIMEN<<TEST<<<<<<<<1", "a digit after filler"),
("SPECIMEN<<TE?T", "a stray character"),
] {
assert!(!name_field_is_grammatical(field), "{why}: {field}");
}
}
const L1: &str = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const L1_OTHER_NAME: &str = "P<UTOERIKSSDN<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const L2: &str = "L898902C36UTO7408122F1204159ZE184226B<<<<<10";
const L2_OTHER_EXPIRY: &str = "L898902C36UTO7408122F1204169ZE184226B<<<<<10";
fn td3(line1: &str, line2: &str) -> MrzData {
parse_td3_with(line1, line2, &ParseOptions::default()).expect("parses")
}
#[test]
fn a_different_name_alone_passes_the_equality_guard() {
let accepted = td3(L1, L2);
let proposal = td3(L1_OTHER_NAME, L2);
assert_ne!(proposal.surname, accepted.surname);
assert!(differs_in_names_only(&proposal, &accepted));
assert!(differs_in_names_only(&accepted, &accepted));
}
#[test]
fn a_different_non_name_field_fails_the_equality_guard() {
let accepted = td3(L1, L2);
let other_line2 = td3(L1_OTHER_NAME, L2_OTHER_EXPIRY);
assert!(!differs_in_names_only(&other_line2, &accepted));
let other_issuer = td3("P<UTPERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<", L2);
assert!(!differs_in_names_only(&other_issuer, &accepted));
let other_code = td3("PDUTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<", L2);
assert!(!differs_in_names_only(&other_code, &accepted));
let mut recovered = td3(L1_OTHER_NAME, L2);
recovered.damaged_recovery = true;
assert!(!differs_in_names_only(&recovered, &accepted));
}
#[test]
fn the_widths_are_the_formats_line_widths() {
assert_eq!(line1_width(Format::Td3), Some(44));
assert_eq!(line1_width(Format::MrvA), Some(44));
assert_eq!(line1_width(Format::Td2), Some(36));
assert_eq!(line1_width(Format::MrvB), Some(36));
assert_eq!(line1_width(Format::Td1), None);
}
}