#![cfg_attr(docsrs, feature(doc_cfg))]
#![warn(missing_docs)]
#![forbid(unsafe_code)]
#[cfg(doctest)]
#[doc = include_str!("../README.md")]
struct ReadmeDoctests;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
#[cfg(feature = "zeroize")]
use zeroize::ZeroizeOnDrop;
mod blindspot;
mod checksum;
mod countries;
mod dates;
mod doccode;
mod emit;
mod line1_select;
mod mrz_date;
mod occlusion;
mod parser;
mod rank;
mod repair;
mod sex;
mod strip;
mod translit;
pub use blindspot::{blindspot, class_of, collisions, Blindspot, CLASSES};
pub use checksum::{check_digit, verify};
pub use countries::{alternate_names, code_for_name, codes, codes_equivalent, country_name};
pub use dates::{
date_completeness, expand_date, expand_date_with_pivot, is_leap_year, Date, DateCompleteness,
DateValidity, CURRENT_YY,
};
pub use doccode::{passport_type, PassportType};
pub use emit::{
encode_name_component, format_mrv_a, format_mrv_b, format_td1, format_td2, format_td3,
MrvAFields, MrvBFields, Td1Fields, Td2Fields, Td3Fields,
};
pub use line1_select::{select_line1, Line1Selection, Line1Unresolved, Line1Verdict};
pub use mrz_date::{DateRole, InvalidRawDateField, MrzDate, ParseMrzDateError, RawDateField};
pub use occlusion::{apply_occlusion, CellMask, Occluded, ZoneField};
pub use parser::{
find_and_parse, find_and_parse_with, parse_mrv_a, parse_mrv_a_with, parse_mrv_b,
parse_mrv_b_with, parse_td1, parse_td1_with, parse_td2, parse_td2_with, parse_td3,
parse_td3_with,
};
pub use repair::{
solve_class_sweep, solve_field, solve_substitution, substitution_candidates, width_candidates,
FieldKind, Resolution, CONFUSABLES, MRZ_ALPHABET, UNKNOWN,
};
pub use sex::{ParseSexError, Sex};
pub use translit::{
transliterate, transliterate_char, transliterate_cyrillic, transliterate_cyrillic_char,
transliterations, CyrillicLanguage, TransliterationStyle,
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct ParseOptions {
pub pivot_yy: u32,
#[cfg_attr(feature = "serde", serde(default))]
pub class_sweep: bool,
}
impl Default for ParseOptions {
fn default() -> Self {
Self {
pivot_yy: CURRENT_YY,
class_sweep: false,
}
}
}
impl ParseOptions {
#[must_use]
pub const fn with_pivot_yy(mut self, pivot_yy: u32) -> Self {
self.pivot_yy = pivot_yy;
self
}
#[must_use]
pub const fn with_class_sweep(mut self, class_sweep: bool) -> Self {
self.class_sweep = class_sweep;
self
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct Checks {
pub document_number: Option<bool>,
pub date_of_birth: Option<bool>,
pub date_of_expiry: Option<bool>,
pub personal_number: Option<bool>,
pub composite: Option<bool>,
}
impl Checks {
pub fn all_valid(&self) -> bool {
self.applicable() > 0 && self.verified() == self.applicable()
}
pub(crate) fn from_verifications(format: Format, verified: [bool; 5]) -> Self {
let applicable = format.check_digit_applicability();
Self {
document_number: applicable[0].then_some(verified[0]),
date_of_birth: applicable[1].then_some(verified[1]),
date_of_expiry: applicable[2].then_some(verified[2]),
personal_number: applicable[3].then_some(verified[3]),
composite: applicable[4].then_some(verified[4]),
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum SequenceCompleteness {
Complete {
checks: Checks,
date_of_birth: DateCompleteness,
},
Partial {
format: Format,
lines_found: u8,
lines_expected: u8,
},
}
impl SequenceCompleteness {
pub fn from_parse_result(result: &Result<MrzData, MrzError>) -> Option<Self> {
match result {
Ok(data) => Some(data.sequence_completeness()),
Err(MrzError::IncompleteSequence {
format,
lines_found,
lines_expected,
}) => Some(Self::Partial {
format: *format,
lines_found: *lines_found,
lines_expected: *lines_expected,
}),
Err(_) => None,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum Format {
Td3,
Td2,
Td1,
MrvA,
MrvB,
}
impl Format {
pub const CHECK_DIGIT_APPLICABILITY: [(Self, [bool; 5]); 5] = [
(Self::Td1, [true, true, true, false, true]),
(Self::Td2, [true, true, true, false, true]),
(Self::Td3, [true, true, true, true, true]),
(Self::MrvA, [true, true, true, false, false]),
(Self::MrvB, [true, true, true, false, false]),
];
pub fn check_digit_applicability(self) -> [bool; 5] {
Self::CHECK_DIGIT_APPLICABILITY
.iter()
.find_map(|(format, applicability)| (*format == self).then_some(*applicability))
.unwrap_or([false; 5])
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[cfg_attr(feature = "zeroize", derive(ZeroizeOnDrop))]
#[non_exhaustive]
pub struct MrzData {
#[cfg_attr(feature = "zeroize", zeroize(skip))]
pub format: Format,
pub document_type: String,
pub issuing_country: String,
pub document_number: String,
pub document_number_full: Option<String>,
#[cfg_attr(feature = "zeroize", zeroize(skip))]
pub document_number_legacy_encoding: bool,
pub surname: String,
pub given_names: String,
pub nationality: String,
pub date_of_birth: MrzDate,
pub sex: Sex,
pub date_of_expiry: MrzDate,
pub optional_data_1: Option<String>,
pub optional_data_2: Option<String>,
pub mrz_lines: String,
#[cfg_attr(feature = "zeroize", zeroize(skip))]
pub checks: Checks,
#[cfg_attr(feature = "zeroize", zeroize(skip))]
#[cfg_attr(feature = "serde", serde(default))]
pub damaged_recovery: bool,
}
impl MrzData {
pub fn checksum_consistent(&self) -> bool {
self.checks.all_valid()
}
pub fn valid(&self) -> bool {
self.checksum_consistent()
}
pub fn full_document_number(&self) -> &str {
self.document_number_full
.as_deref()
.unwrap_or(&self.document_number)
}
pub fn personal_number(&self) -> Option<&str> {
match self.format {
Format::Td3 => self.optional_data_1.as_deref(),
_ => None,
}
}
pub fn issuing_country_name(&self) -> Option<&'static str> {
country_name(&self.issuing_country)
}
pub fn passport_type(&self) -> Option<PassportType> {
passport_type(&self.document_type)
}
pub fn nationality_name(&self) -> Option<&'static str> {
country_name(&self.nationality)
}
pub fn sequence_completeness(&self) -> SequenceCompleteness {
SequenceCompleteness::Complete {
checks: self.checks.clone(),
date_of_birth: self.date_of_birth.completeness(),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub enum Field {
DocumentNumber,
DateOfBirth,
DateOfExpiry,
PersonalNumber,
Composite,
}
impl Field {
pub fn as_str(self) -> &'static str {
match self {
Self::DocumentNumber => "document_number",
Self::DateOfBirth => "date_of_birth",
Self::DateOfExpiry => "date_of_expiry",
Self::PersonalNumber => "personal_number",
Self::Composite => "composite",
}
}
}
impl core::fmt::Display for Field {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
impl Checks {
pub fn applicable(&self) -> u8 {
[
self.document_number,
self.date_of_birth,
self.date_of_expiry,
self.personal_number,
self.composite,
]
.into_iter()
.filter(|check| check.is_some())
.count() as u8
}
pub fn verified(&self) -> u8 {
[
self.document_number,
self.date_of_birth,
self.date_of_expiry,
self.personal_number,
self.composite,
]
.into_iter()
.filter(|check| *check == Some(true))
.count() as u8
}
pub fn failed(&self) -> Vec<Field> {
[
(self.document_number, Field::DocumentNumber),
(self.date_of_birth, Field::DateOfBirth),
(self.date_of_expiry, Field::DateOfExpiry),
(self.personal_number, Field::PersonalNumber),
(self.composite, Field::Composite),
]
.into_iter()
.filter_map(|(ok, f)| (ok == Some(false)).then_some(f))
.collect()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum MrzError {
BadLength {
expected: usize,
got: usize,
},
BadCharacter {
character: char,
line: Option<usize>,
position: usize,
},
BadDocumentCode(String),
BadChecksum {
field: Field,
position: usize,
},
LeadingFiller {
field: Field,
line: usize,
position: usize,
},
IncompleteSequence {
format: Format,
lines_found: u8,
lines_expected: u8,
},
NotFound,
OccludedCheckedCell {
line: usize,
position: usize,
},
}
impl core::fmt::Display for MrzError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::BadLength { expected, got } => {
write!(f, "bad MRZ line length: expected {expected}, got {got}")
}
Self::BadCharacter {
character,
line: Some(line),
position,
} => write!(
f,
"invalid MRZ character: {character:?} at line {line}, column {position}"
),
Self::BadCharacter {
character,
line: None,
position,
} => write!(
f,
"invalid MRZ character: {character:?} at position {position}"
),
Self::BadDocumentCode(c) => write!(f, "unrecognized document code: {c:?}"),
Self::BadChecksum { field, position } => {
write!(f, "check digit failed for {field} at position {position}")
}
Self::LeadingFiller {
field,
line,
position,
} => write!(
f,
"{field} begins with a filler at line {line}, column {position}"
),
Self::IncompleteSequence {
format,
lines_found,
lines_expected,
} => {
write!(
f,
"incomplete {format:?} sequence: found {lines_found} of {lines_expected} lines"
)
}
Self::NotFound => write!(f, "no MRZ found in text"),
Self::OccludedCheckedCell { line, position } => write!(
f,
"occluded cell at line {line}, column {position} cannot be withheld safely"
),
}
}
}
impl std::error::Error for MrzError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn zero_applicable_checks_are_not_valid() {
let checks = Checks {
document_number: None,
date_of_birth: None,
date_of_expiry: None,
personal_number: None,
composite: None,
};
assert_eq!(checks.applicable(), 0);
assert_eq!(checks.verified(), 0);
assert!(!checks.all_valid());
assert!(checks.failed().is_empty());
}
const TD3_L1: &str = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const TD3_L2: &str = "L898902C36UTO7408122F1204159ZE184226B<<<<<10";
#[test]
fn td3_specimen_fully_valid() {
let d = parse_td3(TD3_L1, TD3_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_type, "P");
assert_eq!(d.issuing_country, "UTO");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.document_number, "L898902C3");
assert_eq!(d.nationality, "UTO");
assert_eq!(d.date_of_birth.to_string(), "1974-08-12");
assert_eq!(d.date_of_birth.completeness(), DateCompleteness::Complete);
assert_eq!(d.sex, Sex::Female);
assert_eq!(d.date_of_expiry.to_string(), "2012-04-15");
assert_eq!(d.personal_number(), Some("ZE184226B"));
}
#[test]
fn td3_tampered_dob_fails_checksum() {
let tampered = TD3_L2.replacen("740812", "750812", 1);
let d = parse_td3(TD3_L1, &tampered).unwrap();
assert_eq!(d.checks.date_of_birth, Some(false));
assert_eq!(d.checks.composite, Some(false));
assert!(!d.valid());
}
#[test]
fn td3_all_filler_dob_is_a_valid_field_not_a_bad_read() {
assert_eq!(check_digit("<<<<<<").unwrap(), 0);
let l2 = format!("{}{}{}", &TD3_L2[0..13], "<<<<<<0", &TD3_L2[20..]);
assert_eq!(l2.len(), TD3_L2.len());
let d = parse_td3(TD3_L1, &l2).unwrap();
assert_eq!(d.checks.date_of_birth, Some(true));
assert_eq!(d.date_of_birth, MrzDate::Unknown); assert_eq!(d.date_of_birth.to_string(), "<<<<<<"); assert_eq!(d.date_of_birth.completeness(), DateCompleteness::Unknown);
}
#[test]
fn td3_empty_personal_number_with_filler_check_digit_zero() {
let l2 = "L898902C36UTO7408122F1204159<<<<<<<<<<<<<<08";
let d = parse_td3(TD3_L1, l2).unwrap();
assert_eq!(d.checks.personal_number, Some(true));
assert_eq!(d.checks.composite, Some(true));
assert_eq!(d.personal_number(), None);
}
#[test]
fn td3_empty_personal_number_with_filler_check_digit_filler() {
let l2 = "L898902C36UTO7408122F1204159<<<<<<<<<<<<<<<8";
let d = parse_td3(TD3_L1, l2).unwrap();
assert_eq!(d.checks.personal_number, Some(true));
assert_eq!(d.checks.composite, Some(true));
assert_eq!(d.personal_number(), None);
}
const TD1_L1: &str = "I<UTOD231458907<<<<<<<<<<<<<<<";
const TD1_L2: &str = "7408122F1204159UTO<<<<<<<<<<<6";
const TD1_L3: &str = "ERIKSSON<<ANNA<MARIA<<<<<<<<<<";
#[test]
fn bad_character_reports_zero_based_td1_line_and_column() {
for (line, expected_position) in [(0, 3), (1, 7), (2, 11)] {
let mut lines = [TD1_L1.to_string(), TD1_L2.to_string(), TD1_L3.to_string()];
lines[line].replace_range(expected_position..expected_position + 1, "?");
let error = parse_td1(&lines[0], &lines[1], &lines[2]).unwrap_err();
assert_eq!(
error,
MrzError::BadCharacter {
character: '?',
line: Some(line),
position: expected_position,
}
);
assert_eq!(
error.to_string(),
format!("invalid MRZ character: '?' at line {line}, column {expected_position}")
);
}
}
#[test]
fn bad_character_from_the_standalone_helper_reports_no_line() {
let error = crate::check_digit("L8?8902C3").unwrap_err();
assert_eq!(
error,
MrzError::BadCharacter {
character: '?',
line: None,
position: 2,
}
);
assert_eq!(
error.to_string(),
"invalid MRZ character: '?' at position 2"
);
}
#[test]
fn bad_character_position_counts_chars_not_bytes() {
let e_acute = char::from_u32(0xC9).expect("U+00C9 is a valid scalar value");
let line1 = format!("P<UTO{e_acute}{}", "<".repeat(38));
assert_eq!(
line1.chars().count(),
44,
"char length must satisfy the TD3 gate"
);
assert_eq!(line1.len(), 45);
let error = parse_td3(&line1, &"<".repeat(44)).unwrap_err();
assert_eq!(
error,
MrzError::BadCharacter {
character: e_acute,
line: Some(0),
position: 5,
}
);
}
#[test]
fn td1_specimen_fully_valid() {
let d = parse_td1(TD1_L1, TD1_L2, TD1_L3).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::Td1);
assert_eq!(d.document_type, "I");
assert_eq!(d.document_number, "D23145890");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.date_of_birth.to_string(), "1974-08-12");
assert_eq!(d.date_of_birth.completeness(), DateCompleteness::Complete);
assert_eq!(d.date_of_expiry.to_string(), "2012-04-15");
}
#[test]
fn td1_all_filler_dob_reports_unknown() {
let l2 = format!("{}{}", "<<<<<<0", &TD1_L2[7..]);
assert_eq!(l2.len(), TD1_L2.len());
let d = parse_td1(TD1_L1, &l2, TD1_L3).unwrap();
assert_eq!(d.checks.date_of_birth, Some(true));
assert_eq!(d.date_of_birth, MrzDate::Unknown);
assert_eq!(d.date_of_birth.completeness(), DateCompleteness::Unknown);
}
const TD2_L1: &str = "I<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<";
const TD2_L2: &str = "D231458907UTO7408122F1204159<<<<<<<6";
#[test]
fn sex_cell_is_classified_not_collapsed() {
for (cell, expected) in [
('M', Sex::Male),
('F', Sex::Female),
('<', Sex::Unspecified),
('X', Sex::NonConformant('X')),
('1', Sex::NonConformant('1')),
] {
let mut l2 = TD3_L2.to_string();
l2.replace_range(20..21, &cell.to_string());
let d = parse_td3(TD3_L1, &l2).unwrap();
assert!(d.valid(), "cell {cell:?}: checks {:?}", d.checks);
assert_eq!(d.sex, expected, "cell {cell:?}");
assert_eq!(d.sex.to_string(), cell.to_string());
}
}
#[test]
fn td2_specimen_fully_valid() {
let d = parse_td2(TD2_L1, TD2_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::Td2);
assert_eq!(d.document_type, "I");
assert_eq!(d.issuing_country, "UTO");
assert_eq!(d.document_number, "D23145890");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.nationality, "UTO");
assert_eq!(d.date_of_birth.to_string(), "1974-08-12");
assert_eq!(d.sex, Sex::Female);
assert_eq!(d.date_of_expiry.to_string(), "2012-04-15");
}
#[test]
fn td2_tampered_expiry_fails_checksum() {
let tampered = TD2_L2.replacen("120415", "120416", 1);
let d = parse_td2(TD2_L1, &tampered).unwrap();
assert_eq!(d.checks.date_of_expiry, Some(false));
assert_eq!(d.checks.composite, Some(false));
assert!(!d.valid());
}
#[test]
fn td2_found_in_ocr_text() {
let text = format!("## IDENTITY CARD\n\nnoise\n\n{TD2_L1}\n{TD2_L2}\n\nfooter");
let d = find_and_parse(&text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::Td2);
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.document_number, "D23145890");
}
#[test]
fn find_in_ocr_noise() {
let text = format!(
"## REPUBLIC OF UTOPIA\n\nSome OCR noise here\n\n{}\n{}\n\nfooter",
"p<utoeriksson«anna<maria<<<<<<<<<<<<<<<<<",
"L898902C36UTO7408122F1204159ZE184226B<<<<<10"
);
let d = find_and_parse(&text).unwrap();
assert!(d.valid());
assert_eq!(d.surname, "ERIKSSON");
}
#[test]
fn find_html_escaped_and_merged_lines() {
let text = "## PUTOVNICA\n\nP<HRVSPECIMEN<<SPECIMEN<<<<<<<<<<<<<<<<<<<<< 0070070071HRV8212258F1407019<<<<<<<<<<<<<<06\n";
let d = find_and_parse(text).unwrap();
assert_eq!(d.surname, "SPECIMEN");
assert_eq!(d.document_number, "007007007");
assert_eq!(d.issuing_country, "HRV");
assert_eq!(d.checks.document_number, Some(true));
assert_eq!(d.checks.date_of_birth, Some(true));
assert_eq!(d.checks.date_of_expiry, Some(true));
}
#[test]
fn checksum_verified_ocr_repair() {
let text = "I 01072009 PUJZAGREB 0\n\nBIDFD WH5SS A 2\n\n01072014\nP<HRVSPECIMEN<<SPECIMEN<KLLLLLLLLLLLLLLLLLKLKL\n10070070071HRVB212258F1407019<<<<<<<<<<<<<<06\n";
let d = find_and_parse(text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.surname, "SPECIMEN");
assert_eq!(d.given_names, "SPECIMEN");
assert_eq!(d.document_number, "007007007");
assert_eq!(d.date_of_birth.to_string(), "1982-12-25");
}
#[test]
fn ocr_repair_dropped_filler_mid_line() {
let text = "RF 01072009 PUZAGREB\n01072014\nP<HRVSPECIMEN<<SPECIMEN<<K<KLLLLLLLLLLLLLLLLKLKL\n0070070071HRVB212258F1407019<<<<LLLLLLL<<06\n";
let d = find_and_parse(text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.surname, "SPECIMEN");
assert_eq!(d.document_number, "007007007");
assert_eq!(d.personal_number(), None);
}
#[test]
fn td1_from_single_docling_line_with_k_misreads() {
let text = "1F9874543\n\nIKSVNIE987654302806985505145K< 8506287F3203282SVN<<<<<<<<<<<2 VZORECKKJANAKKKKKKKKK<<KK";
let d = find_and_parse(text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::Td1);
assert_eq!(d.document_type, "IK");
assert_eq!(d.issuing_country, "SVN");
assert_eq!(d.document_number, "IE9876543");
assert_eq!(d.surname, "VZOREC");
assert_eq!(d.given_names, "JANA");
assert_eq!(d.date_of_birth.to_string(), "1985-06-28");
assert_eq!(d.date_of_expiry.to_string(), "2032-03-28");
assert_eq!(d.optional_data_1.as_deref(), Some("2806985505145"));
assert_eq!(d.personal_number(), None, "a TD1 prints no personal number");
}
#[test]
fn ocr_repair_deeply_truncated_name_line() {
let text = "PUTOVNICA\nPKHRVSPECIMEN<<SPECIMEN<<<<<<<<<<<<\n0070070071HRV8212258F1407019<<<<<<<<<<<<<<06\n";
let d = find_and_parse(text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.surname, "SPECIMEN");
assert_eq!(d.given_names, "SPECIMEN");
assert_eq!(d.document_number, "007007007");
}
#[test]
fn invalid_checksums_still_reported() {
let tampered = TD3_L2.replacen("740812", "750812", 1);
let text = format!("{TD3_L1}\n{tampered}");
let d = find_and_parse(&text).unwrap();
assert!(!d.valid());
assert_eq!(d.checks.date_of_birth, Some(false));
}
#[test]
fn find_nothing_in_plain_text() {
assert_eq!(
find_and_parse("just a regular paragraph\nwith two lines"),
Err(MrzError::NotFound)
);
}
const MRV_A_ICAO_L1: &str = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const MRV_A_ICAO_L2: &str = "L898902C<3UTO6908061F9406236ZE184226B<<<<<<<";
const MRV_B_ICAO_L1: &str = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<";
const MRV_B_ICAO_L2: &str = "L898902C<3UTO6908061F9406236ZE184226";
#[test]
fn mrv_a_icao_published_specimen_fully_valid() {
let d = parse_mrv_a(MRV_A_ICAO_L1, MRV_A_ICAO_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvA);
assert_eq!(d.document_type, "V");
assert_eq!(d.issuing_country, "UTO");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.nationality, "UTO");
assert_eq!(d.sex, Sex::Female);
assert_eq!(d.document_number, "L898902C");
assert_eq!(d.document_number_full, None);
assert_eq!(d.optional_data_1.as_deref(), Some("ZE184226B"));
assert_eq!(
d.personal_number(),
None,
"a visa prints no personal number"
);
assert_eq!(d.date_of_birth.to_string(), "1969-08-06");
assert_eq!(d.date_of_expiry.to_string(), "2094-06-23");
}
#[test]
fn mrv_b_icao_published_specimen_fully_valid() {
let d = parse_mrv_b(MRV_B_ICAO_L1, MRV_B_ICAO_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvB);
assert_eq!(d.document_type, "V");
assert_eq!(d.issuing_country, "UTO");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.nationality, "UTO");
assert_eq!(d.document_number, "L898902C");
assert_eq!(d.document_number_full, None);
assert_eq!(d.optional_data_1.as_deref(), Some("ZE184226"));
assert_eq!(
d.personal_number(),
None,
"a visa prints no personal number"
);
assert_eq!(d.date_of_birth.to_string(), "1969-08-06");
assert_eq!(d.date_of_expiry.to_string(), "2094-06-23");
}
const MRV_A_L1: &str = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const MRV_A_L2: &str = "XK93054875BRA8502212F2703143R5T6U7V8W9<<<<<<";
#[test]
fn mrv_a_specimen_fully_valid() {
let d = parse_mrv_a(MRV_A_L1, MRV_A_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvA);
assert_eq!(d.document_type, "V");
assert_eq!(d.issuing_country, "UTO");
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.given_names, "ANNA MARIA");
assert_eq!(d.nationality, "BRA");
assert_eq!(d.date_of_birth.to_string(), "1985-02-21");
assert_eq!(d.sex, Sex::Female);
assert_eq!(d.date_of_expiry.to_string(), "2027-03-14");
assert_eq!(d.document_number, "XK9305487");
assert_eq!(d.optional_data_1.as_deref(), Some("R5T6U7V8W9"));
assert_eq!(
d.personal_number(),
None,
"a visa prints no personal number"
);
}
const MRV_B_L1: &str = "V<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<";
const MRV_B_L2: &str = "L234567897DEU9201017F2706306QW12ER34";
#[test]
fn parser_check_presence_matches_the_format_matrix() {
let expected = [
(Format::Td3, [true, true, true, true, true]),
(Format::Td1, [true, true, true, false, true]),
(Format::Td2, [true, true, true, false, true]),
(Format::MrvA, [true, true, true, false, false]),
(Format::MrvB, [true, true, true, false, false]),
];
for (format, applicability) in expected {
assert_eq!(format.check_digit_applicability(), applicability);
}
let parsed = [
parse_td1(TD1_L1, TD1_L2, TD1_L3).unwrap(),
parse_td2(TD2_L1, TD2_L2).unwrap(),
parse_td3(TD3_L1, TD3_L2).unwrap(),
parse_mrv_a(MRV_A_L1, MRV_A_L2).unwrap(),
parse_mrv_b(MRV_B_L1, MRV_B_L2).unwrap(),
];
for data in parsed {
let observed = [
data.checks.document_number.is_some(),
data.checks.date_of_birth.is_some(),
data.checks.date_of_expiry.is_some(),
data.checks.personal_number.is_some(),
data.checks.composite.is_some(),
];
assert_eq!(
observed,
data.format.check_digit_applicability(),
"{:?}: parser presence must follow the format matrix",
data.format
);
}
}
#[test]
fn mrv_b_specimen_fully_valid() {
let d = parse_mrv_b(MRV_B_L1, MRV_B_L2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvB);
assert_eq!(d.nationality, "DEU");
assert_eq!(d.date_of_birth.to_string(), "1992-01-01");
assert_eq!(d.date_of_expiry.to_string(), "2027-06-30");
assert_eq!(d.document_number, "L23456789");
assert_eq!(d.optional_data_1.as_deref(), Some("QW12ER34"));
assert_eq!(
d.personal_number(),
None,
"a visa prints no personal number"
);
}
#[test]
fn mrv_a_tampered_dob_fails_checksum() {
let tampered = MRV_A_L2.replacen("850221", "860221", 1);
let d = parse_mrv_a(MRV_A_L1, &tampered).unwrap();
assert_eq!(d.checks.date_of_birth, Some(false));
assert!(!d.valid());
}
#[test]
fn mrv_rejects_non_v_document_code() {
let line1 = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
let result = parse_mrv_a(line1, MRV_A_L2);
assert!(matches!(result, Err(MrzError::BadDocumentCode(_))));
}
#[test]
fn mrv_a_found_in_ocr_text() {
let text = format!("## VISA\n\nnoise\n\n{MRV_A_L1}\n{MRV_A_L2}\n\nfooter");
let d = find_and_parse(&text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvA);
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.nationality, "BRA");
}
#[test]
fn mrv_b_found_in_ocr_text() {
let text = format!("## VISA\n\nnoise\n\n{MRV_B_L1}\n{MRV_B_L2}\n\nfooter");
let d = find_and_parse(&text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvB);
assert_eq!(d.nationality, "DEU");
}
#[test]
fn mrv_found_html_escaped_or_merged() {
let escaped_l1 = MRV_A_L1.replace('<', "<");
let escaped_l2 = MRV_A_L2.replace('<', "<");
let text = format!("## VISA\n\n{escaped_l1}\n{escaped_l2}\n");
let d = find_and_parse(&text).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvA);
let merged = format!("## VISA\n\n{MRV_A_L1}{MRV_A_L2}\n");
let d = find_and_parse(&merged).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.format, Format::MrvA);
}
#[test]
fn td3_long_document_number_round_trips() {
let fields = Td3Fields {
document_code: "P".into(),
issuing_country: "UTO".into(),
document_number: "L898902C31234".into(), surname: "ERIKSSON".into(),
given_names: "ANNA MARIA".into(),
nationality: "UTO".into(),
date_of_birth: MrzDate::Calendar(Date::new(1974, 8, 12)),
sex: Sex::Female,
date_of_expiry: MrzDate::Calendar(Date::new(2012, 4, 15)),
personal_number: None,
};
let mrz = format_td3(&fields);
let (l1, l2) = mrz.split_once('\n').unwrap();
assert_eq!(&l2[0..10], "L898902C3<");
let d = parse_td3(l1, l2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_number_full.as_deref(), Some("L898902C31234"));
assert_eq!(d.full_document_number(), "L898902C31234");
assert!(!d.document_number_legacy_encoding);
assert_eq!(d.document_number, "L898902C3");
assert_eq!(d.personal_number(), None);
}
#[test]
fn overflow_coexists_with_personal_number() {
let fields = Td3Fields {
document_number: "AB1234567890".into(), personal_number: Some("ZE184".into()),
..Td3Fields::default()
};
let d = parse_td3_str(&format_td3(&fields));
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_number_full.as_deref(), Some("AB1234567890"));
assert_eq!(d.personal_number(), Some("ZE184"));
}
#[test]
fn td2_and_td1_long_document_numbers_round_trip() {
let td2 = Td2Fields {
document_number: "D23145890XY".into(), date_of_birth: MrzDate::Calendar(Date::new(1974, 8, 12)),
date_of_expiry: MrzDate::Calendar(Date::new(2012, 4, 15)),
..Td2Fields::default()
};
let mrz = format_td2(&td2);
let (l1, l2) = mrz.split_once('\n').unwrap();
let d = parse_td2(l1, l2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_number_full.as_deref(), Some("D23145890XY"));
let td1 = Td1Fields {
document_number: "D23145890ABCDE".into(), date_of_birth: MrzDate::Calendar(Date::new(1974, 8, 12)),
date_of_expiry: MrzDate::Calendar(Date::new(2012, 4, 15)),
..Td1Fields::default()
};
let mrz = format_td1(&td1);
let mut lines = mrz.lines();
let d = parse_td1(
lines.next().unwrap(),
lines.next().unwrap(),
lines.next().unwrap(),
)
.unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_number_full.as_deref(), Some("D23145890ABCDE"));
}
#[test]
fn overflow_remainder_too_long_falls_back_to_truncation() {
let td2 = Td2Fields {
document_number: "D23145890ABCDEF".into(), date_of_birth: MrzDate::Calendar(Date::new(1974, 8, 12)),
date_of_expiry: MrzDate::Calendar(Date::new(2012, 4, 15)),
..Td2Fields::default()
};
let mrz = format_td2(&td2);
let (l1, l2) = mrz.split_once('\n').unwrap();
let d = parse_td2(l1, l2).unwrap();
assert!(d.valid(), "checks: {:?}", d.checks);
assert_eq!(d.document_number_full, None);
assert_eq!(d.document_number, "D23145890");
}
#[test]
fn tampered_overflow_remainder_fails_the_check_digit() {
let fields = Td3Fields {
document_number: "L898902C31234".into(),
..Td3Fields::default()
};
let mrz = format_td3(&fields);
let tampered = mrz.replacen("1234", "1235", 1);
let d = parse_td3_str(&tampered);
assert_eq!(d.checks.document_number, Some(false));
assert!(!d.valid());
assert!(d.checks.failed().contains(&Field::DocumentNumber));
}
#[test]
fn ordinary_specimens_report_no_overflow() {
assert_eq!(
parse_td3(TD3_L1, TD3_L2).unwrap().document_number_full,
None
);
assert_eq!(
parse_td1(TD1_L1, TD1_L2, TD1_L3)
.unwrap()
.document_number_full,
None
);
assert_eq!(
parse_td2(TD2_L1, TD2_L2).unwrap().document_number_full,
None
);
}
#[test]
fn blank_document_number_is_refused_not_read_as_overflow() {
let blank = "<<<<<<<<<<UTO7408122F1204159<<<<<<<<<<<<<<02";
assert_eq!(
parse_td3(TD3_L1, blank),
Err(MrzError::LeadingFiller {
field: Field::DocumentNumber,
line: 1,
position: 0,
})
);
}
fn parse_td3_str(mrz: &str) -> MrzData {
let (l1, l2) = mrz.split_once('\n').unwrap();
parse_td3(l1, l2).unwrap()
}
#[test]
fn pivot_is_configurable_per_call() {
let d = parse_td3(TD3_L1, TD3_L2).unwrap();
assert_eq!(d.date_of_birth.to_string(), "1974-08-12");
let opts = ParseOptions::default().with_pivot_yy(80);
let d = parse_td3_with(TD3_L1, TD3_L2, &opts).unwrap();
assert_eq!(d.date_of_birth.to_string(), "2074-08-12");
assert!(d.valid());
}
#[test]
fn default_options_match_the_plain_entry_points() {
let opts = ParseOptions::default();
assert_eq!(opts.pivot_yy, CURRENT_YY);
assert_eq!(
parse_td3(TD3_L1, TD3_L2).unwrap(),
parse_td3_with(TD3_L1, TD3_L2, &opts).unwrap()
);
let text = format!("## VISA\n\n{MRV_A_L1}\n{MRV_A_L2}\n");
assert_eq!(
find_and_parse(&text).unwrap(),
find_and_parse_with(&text, &opts).unwrap()
);
}
#[test]
fn failed_lists_the_failing_fields() {
let clean = parse_td3(TD3_L1, TD3_L2).unwrap();
assert!(clean.checks.failed().is_empty());
let tampered = TD3_L2.replacen("740812", "750812", 1);
let d = parse_td3(TD3_L1, &tampered).unwrap();
assert_eq!(
d.checks.failed(),
vec![Field::DateOfBirth, Field::Composite]
);
assert_eq!(Field::DateOfBirth.to_string(), "date_of_birth");
}
#[test]
fn scanner_keeps_the_best_scoring_partial_read() {
let tampered = TD3_L2
.replacen("740812", "750812", 1)
.replacen("120415", "120416", 1);
let text = format!("noise\n\n{TD3_L1}\n{tampered}\n\nfooter");
let d = find_and_parse(&text).unwrap();
assert!(!d.valid());
assert_eq!(d.surname, "ERIKSSON");
assert_eq!(d.document_number, "L898902C3");
assert_eq!(d.checks.document_number, Some(true));
assert_eq!(d.checks.date_of_birth, Some(false));
assert_eq!(d.checks.date_of_expiry, Some(false));
}
#[test]
fn country_names_surface_on_mrzdata() {
let d = parse_td1(TD1_L1, TD1_L2, TD1_L3).unwrap();
assert_eq!(d.issuing_country_name(), Some("Utopia (ICAO specimen)"));
assert_eq!(d.nationality_name(), Some("Utopia (ICAO specimen)"));
}
}