mrz 0.9.1

Zero-dependency (by default) ICAO 9303 Machine Readable Zone (MRZ) parser, emitter, and check-digit validator for TD1/TD2/TD3 and MRV-A/MRV-B (visa) documents.
Documentation
//! What a check digit provably *cannot* catch.
//!
//! The closed-form law, its inversion of the usual OCR intuition, and what
//! changes once a misread spans more than one character are documented on
//! [`Blindspot`], which is the public face of this module.

use crate::checksum::char_value;

/// Whether a check digit can distinguish two MRZ characters.
///
/// An ICAO 9303 check digit (Part 3 §4.9) is the 7-3-1 weighted sum of the
/// character values `0-9 → 0-9`, `A-Z → 10-35`, `< → 0`, taken **mod 10**.
/// A single-character substitution shifts the sum by
/// `weight × (value(a) - value(b))`, and that shift vanishes mod 10 for
/// *every* weight exactly when the two values are congruent mod 10.
///
/// That gives a complete, closed-form law:
///
/// > Two MRZ characters are indistinguishable to every check digit **iff**
/// > their ICAO values are congruent mod 10.
///
/// The consequence inverts most people's intuition. The OCR confusions that
/// get worried about most — O↔0, I↔1, B↔8, S↔5, Z↔2 — are all **caught**,
/// because letters sit 10..35 and their digit lookalikes do not line up mod
/// 10. The quiet pairs K↔`<`, I↔S, B↔L and A↔K are **blind**, and no amount
/// of check-digit arithmetic will ever separate them.
///
/// ```
/// use mrz::{blindspot, Blindspot};
///
/// // The classic OCR worry is not the dangerous one.
/// assert!(matches!(blindspot('O', '0'), Blindspot::Caught { .. }));
/// // This one is invisible to every check digit ever printed.
/// assert!(blindspot('K', '<').is_blind());
/// ```
///
/// [`CLASSES`] is the complete atlas of the blind pairs, and
/// `cargo run -p mrz --example checksum_blindspots` demonstrates the same law
/// empirically against the real parser rather than asserting the algebra.
///
/// # The law is pairwise; real misreads usually are not
///
/// Everything above is stated for **one** substituted character, which is what
/// [`blindspot`] takes and all this type can express. Measured against a real
/// corpus, only about a third of document-number misreads are single-character
/// (25 of 76; see
/// `knowledge/benchmarks/checksum-blindspots-measured-2026-08-05.md`).
///
/// Across k substituted positions the sum shifts by `Σ Δᵢ·wᵢ (mod 10)`, so
/// individually-**caught** substitutions cancel one another. The common case is
/// two O↔0 at weights 7 and 3: `24·(7+3) = 240 ≡ 0`. Separately each is caught
/// (`24·7 ≡ 8`, `24·3 ≡ 2`); together they are invisible. In a 9-character
/// document number the weights run 7,3,1,7,3,1,7,3,1, so that (7,3) pairing
/// joins any of the weight-7 positions 0, 3, 6 to any of the weight-3
/// positions 1, 4, 7: nine of the 36 position pairs — structural, not a fluke.
/// A shared shift of 5, such as two `2`↔`7` misreads, cancels at every pair,
/// because the sum of two odd weights is even.
///
/// So read the law as *"which single swaps are safe"*, not as *"which
/// characters are safe"*. Empirically the undetectable set is dominated by the
/// pairs it calls caught — O↔0 alone accounts for 44 of those 76 rows —
/// precisely because they arrive in combinations. Of the quiet pairs named as
/// the real danger, exactly one K↔`<` appears in the whole corpus.
///
/// This is why the crate layers structural guards on top of the arithmetic
/// (country-code recognition and date plausibility in the scanner
/// repair gates; direct `parse_*` calls do not apply those guards): the oracle is
/// exact, and it is exact about its own edges too. It is a strong *filter* — it
/// rejects most misreads — and a weak *oracle*: what it passes is not a random
/// remainder but specifically what the arithmetic cannot see.
///
/// Obtain one from [`blindspot`]. `#[non_exhaustive]`: a future variant (e.g.
/// for a format whose check digit is not mod 10) must not be a breaking change.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Blindspot {
    /// Same character — there is nothing to distinguish.
    Identical,
    /// Values differ mod 10: any check digit covering the position rejects
    /// the swap. `delta_mod10` is the (non-zero) shift it would induce.
    Caught {
        /// The (non-zero) shift mod 10 the swap would induce in a check digit
        /// covering this position, measured as `value(a) - value(b)` for a
        /// call of `blindspot(a, b)` — that is, the shift from putting `a`
        /// where `b` was.
        ///
        /// **This payload is direction-dependent even though the verdict is
        /// not.** `blindspot(a, b)` and `blindspot(b, a)` agree on
        /// `Caught` vs [`Blind`](Blindspot::Blind) — congruence is symmetric —
        /// but report complementary shifts. `blindspot('P', 'L')` is
        /// `Caught { delta_mod10: 4 }` and `blindspot('L', 'P')` is
        /// `Caught { delta_mod10: 6 }`, describing the one swap from its two
        /// ends. Pass the *candidate* first to read the shift it would
        /// introduce.
        delta_mod10: u32,
    },
    /// Values are congruent mod 10: the swap is provably undetectable by
    /// check digits alone. `residue` is the shared value class.
    Blind {
        /// The value class (0-9) both characters share mod 10.
        residue: u32,
    },
    /// One or both characters lie outside the ICAO 9303 MRZ alphabet.
    NotMrzCharset,
}

impl Blindspot {
    /// `true` only for [`Blindspot::Blind`] — a substitution no check digit
    /// can see. [`Identical`](Blindspot::Identical) is deliberately *not*
    /// blind: nothing was substituted.
    ///
    /// ```
    /// use mrz::blindspot;
    ///
    /// assert!(blindspot('B', 'L').is_blind()); // 11 vs 21: congruent mod 10
    /// assert!(!blindspot('B', '8').is_blind()); // 11 vs 8: caught
    /// assert!(!blindspot('A', 'A').is_blind()); // identical: nothing substituted
    /// ```
    pub fn is_blind(self) -> bool {
        matches!(self, Self::Blind { .. })
    }
}

/// Classify a single-character substitution: can any ICAO check digit tell
/// `a` from `b`?
///
/// ```
/// use mrz::{blindspot, Blindspot};
///
/// assert_eq!(blindspot('A', 'A'), Blindspot::Identical);
/// assert_eq!(blindspot('A', 'K'), Blindspot::Blind { residue: 0 });
/// assert_eq!(blindspot('O', '0'), Blindspot::Caught { delta_mod10: 4 });
/// assert_eq!(blindspot('a', 'A'), Blindspot::NotMrzCharset);
/// ```
pub fn blindspot(a: char, b: char) -> Blindspot {
    let (va, vb) = match (char_value(a), char_value(b)) {
        (Some(va), Some(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 }
    }
}

/// The ten residue classes partitioning the 37-character MRZ alphabet:
/// `CLASSES[r]` lists every character whose ICAO value is ≡ `r` (mod 10).
///
/// This is the complete atlas of undetectable substitutions — any swap
/// *within* a row is invisible to every check digit, and any swap *across*
/// rows is caught. Note class 0 has five members because `<` and `0` share
/// the value 0.
///
/// ```
/// use mrz::{blindspot, CLASSES, MRZ_ALPHABET};
///
/// // Every swap inside a row is blind ...
/// for row in CLASSES {
///     for &a in row {
///         for &b in row {
///             assert!(a == b || blindspot(a, b).is_blind());
///         }
///     }
/// }
/// // ... and the rows partition the whole 37-character alphabet.
/// assert_eq!(CLASSES.iter().map(|row| row.len()).sum::<usize>(), MRZ_ALPHABET.len());
/// ```
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'],
];

/// The residue class `c` belongs to, as a borrowed row of [`CLASSES`], or
/// `None` when `c` is outside the MRZ alphabet. Allocation-free.
///
/// ```
/// // 'K' has ICAO value 20 ≡ 0 (mod 10) — the class `<`/`0` also live in.
/// assert_eq!(mrz::class_of('K'), Some(&['0', 'A', 'K', 'U', '<'][..]));
/// assert_eq!(mrz::class_of('@'), None);
/// ```
pub fn class_of(c: char) -> Option<&'static [char]> {
    char_value(c).map(|v| CLASSES[(v % 10) as usize])
}

/// Every MRZ character a check digit cannot distinguish from `c`, excluding
/// `c` itself. Empty when `c` is outside the alphabet.
///
/// ```
/// use mrz::collisions;
///
/// assert_eq!(collisions('K'), vec!['0', 'A', 'U', '<']);
/// assert!(collisions('@').is_empty());
/// ```
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 });
            }
            // Everything outside the class is caught.
            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());
    }
}