use crate::MrzError;
pub(crate) fn char_value(c: char) -> Option<u32> {
match c {
'0'..='9' => Some(c as u32 - '0' as u32),
'A'..='Z' => Some(c as u32 - 'A' as u32 + 10),
'<' => Some(0),
_ => None,
}
}
pub fn check_digit(field: &str) -> Result<u32, MrzError> {
const WEIGHTS: [u32; 3] = [7, 3, 1];
let mut sum = 0u32;
for (i, c) in field.chars().enumerate() {
sum += char_value(c).ok_or(MrzError::BadCharacter {
character: c,
line: None,
position: i,
})? * WEIGHTS[i % 3];
}
Ok(sum % 10)
}
pub fn verify(field: &str, digit: char) -> bool {
match (check_digit(field), char_value(digit)) {
(Ok(expected), Some(got)) => expected == got && (digit.is_ascii_digit() || digit == '<'),
_ => false,
}
}
pub(crate) fn normalize_line(line: &str) -> String {
let mut out = String::with_capacity(line.len());
for c in line.chars().filter(|c| !c.is_whitespace()) {
match c {
'«' | '≪' => out.push_str("<<"),
'‹' => out.push('<'),
c => out.push(c.to_ascii_uppercase()),
}
}
out
}
pub(crate) fn is_mrz_charset(s: &str) -> bool {
s.chars().all(|c| matches!(c, 'A'..='Z' | '0'..='9' | '<'))
}
pub(crate) fn digitize(c: char) -> char {
match c {
'O' | 'Q' | 'D' => '0',
'I' | 'L' => '1',
'Z' => '2',
'S' => '5',
'G' => '6',
'B' => '8',
c => c,
}
}
pub(crate) fn letterize(c: char) -> char {
match c {
'0' => 'O',
'1' => 'I',
'2' => 'Z',
'5' => 'S',
'6' => 'G',
'8' => 'B',
c => c,
}
}
pub(crate) fn defiller(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = String::with_capacity(s.len());
let mut i = 0;
while i < bytes.len() {
if matches!(bytes[i], b'K' | b'L') {
let mut j = i;
while j < bytes.len() && matches!(bytes[j], b'K' | b'L' | b'<') {
j += 1;
}
let kl = bytes[i..j]
.iter()
.filter(|b| matches!(b, b'K' | b'L'))
.count();
if j - i >= 4 && kl >= 3 {
out.extend(std::iter::repeat_n('<', j - i));
} else {
out.push_str(&s[i..j]);
}
i = j;
} else {
out.push(bytes[i] as char);
i += 1;
}
}
out
}
pub(crate) type RepairRule = (core::ops::Range<usize>, fn(char) -> char);
pub(crate) fn repair_positions(line: &str, spec: &[RepairRule]) -> String {
line.chars()
.enumerate()
.map(|(i, c)| {
if c == '<' {
return c; }
for (range, fix) in spec {
if range.contains(&i) {
return fix(c);
}
}
c
})
.collect()
}
pub(crate) fn fix_doc_code(l: &str) -> String {
if l.as_bytes().first() == Some(&b'P') && l.as_bytes().get(1) == Some(&b'K') {
format!("{}<{}", &l[0..1], &l[2..])
} else {
l.to_string()
}
}
pub(crate) fn fix_name_separator(s: &str) -> String {
let trimmed = s.trim_end_matches('<');
if !trimmed.contains("<<") {
if let Some(pos) = trimmed.find("KK") {
return format!("{}<<{}", &s[..pos], &s[pos + 2..]);
}
}
s.to_string()
}
pub(crate) const MAX_DEFILL_PASSES: usize = 64;
pub(crate) fn aggressive_defiller(s: &str) -> String {
let mut b: Vec<u8> = s.bytes().collect();
let mut changed = true;
let mut passes = 0;
while changed && passes < MAX_DEFILL_PASSES {
changed = false;
passes += 1;
for i in 0..b.len() {
if matches!(b[i], b'K' | b'L')
&& ((i > 0 && b[i - 1] == b'<') || (i + 1 < b.len() && b[i + 1] == b'<'))
{
b[i] = b'<';
changed = true;
}
}
}
String::from_utf8(b).expect("ascii in, ascii out")
}
fn longest_filler_run(s: &str) -> Option<(usize, usize)> {
let mut best: Option<(usize, usize)> = None;
let bytes = s.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b'<' {
let start = i;
while i < bytes.len() && bytes[i] == b'<' {
i += 1;
}
if best.is_none_or(|(_, l)| i - start > l) {
best = Some((start, i - start));
}
} else {
i += 1;
}
}
best
}
pub(crate) fn fit_length(n: &str, target: usize) -> Vec<String> {
use core::cmp::Ordering;
match n.len().cmp(&target) {
Ordering::Equal => vec![n.to_string()],
Ordering::Less => {
let missing = target - n.len();
let mut v = Vec::new();
if let Some((start, len)) = longest_filler_run(n) {
let mut s = String::with_capacity(target);
s.push_str(&n[..start + len]);
s.extend(core::iter::repeat_n('<', missing));
s.push_str(&n[start + len..]);
v.push(s);
}
let mut padded = n.to_string();
padded.extend(core::iter::repeat_n('<', missing));
v.push(padded);
v
}
Ordering::Greater => {
let extra = n.len() - target;
let mut v = Vec::new();
if let Some((start, len)) = longest_filler_run(n) {
if len > extra {
let mut s = String::with_capacity(target);
s.push_str(&n[..start]);
s.extend(core::iter::repeat_n('<', len - extra));
s.push_str(&n[start + len..]);
v.push(s);
}
}
v.push(n[0..target].to_string());
v.push(n[n.len() - target..].to_string());
v
}
}
}
pub(crate) fn variants(raw: &str, target: usize, repair: fn(&str) -> String) -> Vec<String> {
let n = normalize_line(raw);
if n.len() + 14 < target || n.len() > target + 4 || !is_mrz_charset(&n) {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for fitted in fit_length(&n, target) {
let repaired = repair(&fitted);
let last_resort = aggressive_defiller(&repaired);
for form in [repaired, fitted, last_resort] {
if !out.contains(&form) {
out.push(form);
}
}
}
out
}
fn fit_line1_length(n: &str, target: usize) -> Vec<String> {
if n.len() >= target {
return fit_length(n, target);
}
let skip_inflate = matches!(longest_filler_run(n), Some((start, _)) if start < 5);
let mut v = fit_length(n, target);
if skip_inflate && v.len() > 1 {
v.remove(0);
}
v
}
pub(crate) fn line1_variants(raw: &str, target: usize, repair: fn(&str) -> String) -> Vec<String> {
let n = normalize_line(raw);
if n.len() + 14 < target || n.len() > target + 4 || !is_mrz_charset(&n) {
return Vec::new();
}
let mut out: Vec<String> = Vec::new();
for fitted in fit_line1_length(&n, target) {
let repaired = repair(&fitted);
let last_resort = aggressive_defiller(&repaired);
for form in [repaired, fitted, last_resort] {
if !out.contains(&form) {
out.push(form);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn check_digit_icao_vectors() {
assert_eq!(check_digit("L898902C3").unwrap(), 6);
assert_eq!(check_digit("740812").unwrap(), 2);
assert_eq!(check_digit("120415").unwrap(), 9);
assert_eq!(check_digit("ZE184226B<<<<<").unwrap(), 1);
}
#[test]
fn all_filler_date_check_digit_is_zero() {
assert_eq!(check_digit("<<<<<<").unwrap(), 0);
}
#[test]
fn aggressive_defiller_terminates_on_adversarial_runs() {
let s = format!("<{}", "KL".repeat(21)); assert_eq!(aggressive_defiller(&s), "<".repeat(43));
let untouched = "KLKLKLKLKL";
assert_eq!(aggressive_defiller(untouched), untouched);
assert_eq!(aggressive_defiller("AB<KL<CD").len(), 8);
}
#[test]
fn doc_code_repair_preserves_legal_second_position_k() {
assert_eq!(fix_doc_code("PKUTO"), "P<UTO");
for code in ["IKUTO", "AKUTO", "CKUTO", "VKUTO"] {
assert_eq!(fix_doc_code(code), code);
}
}
#[test]
fn name_separator_fix_spares_real_kk_names() {
assert_eq!(
fix_name_separator("MIKKONEN<<HEIKKI<<<<<<"),
"MIKKONEN<<HEIKKI<<<<<<"
);
assert_eq!(fix_name_separator("VZORECKKJANA<<<"), "VZOREC<<JANA<<<");
}
#[test]
fn line1_fit_pads_the_tail_when_the_only_run_starts_before_the_name_field() {
let n = "P<CANMARTIN";
let ordinary = fit_length(n, 20);
assert_eq!(
ordinary.len(),
2,
"sanity: fit_length still offers the inflate candidate here"
);
assert_eq!(
fit_line1_length(n, 20),
vec![ordinary[1].clone()],
"only fit_length's tail-padded candidate must survive"
);
}
#[test]
fn line1_fit_matches_fit_length_when_the_longest_run_starts_at_or_after_the_name_field() {
let n = "P<CANDOE<<<<<JAMESON";
assert_eq!(fit_length(n, 25).len(), 2);
assert_eq!(fit_line1_length(n, 25), fit_length(n, 25));
}
#[test]
fn line1_fit_pads_the_tail_for_a_germany_style_d_filler_issuer_slot() {
let n = "P<D<<SCHWARZENEGGER<<REYNALDALEXANDER";
assert_eq!(n.len(), 37);
let ordinary = fit_length(n, 44);
assert_eq!(
ordinary.len(),
2,
"sanity: fit_length still offers the inflate candidate here"
);
assert_ne!(
ordinary[0], ordinary[1],
"sanity: the inflate and tail-padded candidates must differ"
);
assert_eq!(
fit_line1_length(n, 44),
vec![ordinary[1].clone()],
"only fit_length's tail-padded candidate must survive"
);
}
#[test]
fn line1_fit_matches_fit_length_for_exact_width_and_too_long_lines() {
let exact = "P<CANMARTIN<<SARA<<<<";
let target = exact.len();
assert_eq!(fit_line1_length(exact, target), fit_length(exact, target));
assert_eq!(fit_line1_length(exact, target), vec![exact.to_string()]);
let too_long = "P<CANMARTIN<<<<<<<<<<<SARA<<<<<<<<<<<<<<<<<<<<";
assert!(too_long.len() > target);
assert_eq!(
fit_line1_length(too_long, target),
fit_length(too_long, target)
);
}
}