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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
//! ICAO 9303 check-digit math and generic OCR-repair primitives.
//!
//! A check digit is deterministic evidence rather than a model score: it
//! either agrees with the candidate or it does not. What agreement establishes
//! is *checksum consistency* over the field that digit covers — never
//! byte-identity with the printed zone, which no check digit can establish
//! (see [`crate::Blindspot`]). The repair helpers generate candidate readings
//! of noisy OCR which that same arithmetic then accepts or rejects — see
//! [`crate::find_and_parse`].

use crate::MrzError;

/// ICAO 9303 character value: `0-9 → 0-9`, `A-Z → 10-35`, `< → 0`.
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,
    }
}

/// Compute the ICAO 9303 check digit (part 3 §4.9: 7-3-1 repeating weights,
/// mod 10).
///
/// The `mod 10` is what makes the oracle exact *and* bounded — see
/// [`Blindspot`](crate::Blindspot) for the substitutions it provably cannot
/// catch.
///
/// ```
/// assert_eq!(mrz::check_digit("L898902C3").unwrap(), 6);
/// ```
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)
}

/// Verify `field` against its printed check digit character.
/// A `<` check digit counts as 0; ICAO permits it for an unused TD3 personal number (Part 4 §4.2.2.2).
///
/// ```
/// assert!(mrz::verify("L898902C3", '6'));
/// assert!(!mrz::verify("L898902C3", '0'));
/// ```
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,
    }
}

/// Normalize one line of OCR output toward the MRZ charset:
/// uppercase, strip whitespace, map common OCR confusions of the filler —
/// `«`/`≪` are how OCR typically renders the double filler `<<`, while `‹`
/// is a single `<`.
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' | '<'))
}

/// OCR lookalike corrections for positions that must be digits.
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,
    }
}

/// OCR lookalike corrections for positions that must be letters (or filler).
pub(crate) fn letterize(c: char) -> char {
    match c {
        '0' => 'O',
        '1' => 'I',
        '2' => 'Z',
        '5' => 'S',
        '6' => 'G',
        '8' => 'B',
        c => c,
    }
}

/// Replace runs of ≥ `min_run` consecutive `K`/`L` characters with fillers —
/// OCR persistently misreads the `<` filler as K or L, and no transliterated
/// ICAO name contains four K/L in a row.
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
}

/// One per-index repair rule: apply `fix` to any character at an index inside `range`.
pub(crate) type RepairRule = (core::ops::Range<usize>, fn(char) -> char);

/// Apply a per-index repair map: `spec` lists `(range, fix)` pairs.
pub(crate) fn repair_positions(line: &str, spec: &[RepairRule]) -> String {
    line.chars()
        .enumerate()
        .map(|(i, c)| {
            if c == '<' {
                return c; // fillers are always legitimate
            }
            for (range, fix) in spec {
                if range.contains(&i) {
                    return fix(c);
                }
            }
            c
        })
        .collect()
}

/// Fix a passport-code second character misread: Part 4 §4.4 has no `PK`,
/// but OCR can read the `<` filler in `P<` as `K`. Other formats permit `K`.
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()
    }
}

/// MRZ name fields separate surname from given names with `<<`. When a name
/// field has no `<<` at all but contains `KK`, that pair is a misread
/// separator. Fields that already contain a real `<<` (e.g. MIKKO<<HEIKKI)
/// are left untouched.
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()
}

/// Hard bound on [`aggressive_defiller`]'s convergence loop.
///
/// Each pass that changes anything converts at least one `K`/`L` to `<` and
/// never converts back, so the loop provably terminates within `s.len() + 1`
/// passes; MRZ lines are at most 44 characters. The bound is belt-and-braces
/// against a future rule that could reintroduce characters — it makes
/// termination a property of the code rather than of the argument above it.
pub(crate) const MAX_DEFILL_PASSES: usize = 64;

/// Last-resort variant: any `K`/`L` touching a `<` becomes `<` (to fixpoint,
/// or [`MAX_DEFILL_PASSES`], whichever comes first).
/// Only ever accepted when the composite check digit validates the result.
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")
}

/// Longest run of consecutive `<` fillers: `(start, len)`.
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
}

/// Candidate alignments of a wrong-length line. OCR drops or hallucinates
/// characters most often inside filler runs, so besides trimming/padding at
/// the ends we also inflate/deflate the longest `<` run.
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
        }
    }
}

/// Candidate readings of one OCR line for a given MRZ line length:
/// normalized, length-adjusted, each both verbatim and lookalike-repaired.
/// The check digits decide which variant — if any — is the true read.
pub(crate) fn variants(raw: &str, target: usize, repair: fn(&str) -> String) -> Vec<String> {
    let n = normalize_line(raw);
    // OCR drops trailing fillers wholesale — ocrs truncates a TD3 name line's
    // filler run by 9+ characters on low-resolution scans — so tolerate short
    // lines generously (they get padded back); hallucinated extra characters
    // are rarer. Every padded candidate still has to satisfy the check digits,
    // so a wider net costs candidates, not correctness.
    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
}

/// [`fit_length`] for line 1 of a two-line format (TD3/TD2/MRV-A/MRV-B):
/// on a short line, never inflates a `<` run that starts before index 5 —
/// the document-code filler (index 1, the second cell of a `P<`-style code)
/// and every cell of the three-cell issuing-state slot (indices 2..5), such
/// as a `D<<` issuer — since index 5 is where the name field starts.
///
/// Line 1 of every two-line format carries no check digit (Doc 9303 Part 4
/// §4.2.1 and its TD1/TD2/MRV analogues), so nothing arbitrates a wrong
/// candidate here the way a check digit would on line 2: the first candidate
/// that pairs with a checksum-valid line 2 wins outright. OCR's dropped
/// fillers are overwhelmingly from the name field's own trailing padding,
/// not the three-cell document-code/issuer prefix, so inflating a run that
/// starts inside that prefix manufactures a wrong issuer (or document code)
/// that nothing downstream catches. When the longest run starts at index 5
/// or later, this is byte-identical to [`fit_length`]; exact-width and
/// too-long lines are always byte-identical to it.
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 {
        // `fit_length`'s short-line branch always pushes the inflate
        // candidate first (when a filler run exists) and the tail-padded
        // candidate last; dropping the first here is exactly "pad the tail
        // instead" for a run that starts inside the document-code/issuer
        // prefix, with no separate candidate-construction code to drift
        // from `fit_length`'s own.
        v.remove(0);
    }
    v
}

/// [`variants`] for line 1 of a two-line format (TD3/TD2/MRV-A/MRV-B) — see
/// [`fit_line1_length`] for how it differs. Every other candidate-building
/// path (checked lines, TD1's three lines, [`crate::repair::solve_class_sweep`])
/// keeps calling [`variants`]/[`fit_length`] directly and is unaffected.
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() {
        // Doc 9303 Part 3 §4.8 (`:547`) lets an issuer complete an unknown
        // date of birth with `<`; `:563` gives a `<` the value zero for
        // check-digit purposes. Six fillers therefore sum to zero under the
        // 7-3-1 weighting: `<<<<<<0` is a *valid* field, not a corrupt read.
        assert_eq!(check_digit("<<<<<<").unwrap(), 0);
    }

    #[test]
    fn aggressive_defiller_terminates_on_adversarial_runs() {
        // Worst case for the convergence loop: a solid K/L run anchored by a
        // single filler at one end, so each pass can only eat one character.
        let s = format!("<{}", "KL".repeat(21)); // 43 chars, one seed filler
        assert_eq!(aggressive_defiller(&s), "<".repeat(43));
        // No filler to seed from: nothing is touched, and it still returns.
        let untouched = "KLKLKLKLKL";
        assert_eq!(aggressive_defiller(untouched), untouched);
        // Length is always preserved.
        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() {
        // MIKKONEN<<HEIKKI already contains a real `<<` separator — the KK
        // pairs inside the names must survive.
        assert_eq!(
            fix_name_separator("MIKKONEN<<HEIKKI<<<<<<"),
            "MIKKONEN<<HEIKKI<<<<<<"
        );
        // No separator at all + a KK pair → it was the separator.
        assert_eq!(fix_name_separator("VZORECKKJANA<<<"), "VZOREC<<JANA<<<");
    }

    #[test]
    fn line1_fit_pads_the_tail_when_the_only_run_starts_before_the_name_field() {
        // A short line 1 whose name-field padding was lost (`P<CANMARTIN`,
        // with its document-code filler intact) has exactly one `<` run, at
        // index 1 — before index 5, where the name field starts. `fit_length` inflates it,
        // shifting the issuing-state slot's own bytes into filler;
        // `fit_line1_length` must pad the tail instead.
        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() {
        // The longest run (five cells, starting at index 8) sits inside the
        // name field, not the document-code/issuer prefix, so this must be
        // byte-identical to `fit_length`.
        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() {
        // `D<<` (Germany's legacy single-letter code) and the name's own
        // `<<` separator tie at length 2; `longest_filler_run`'s tie rule
        // keeps the first (start 3, inside the issuing-state slot) — so
        // this exercises the same "starts before index 5" gate as the
        // single-run case above, via a tie rather than an outright maximum.
        // The fillers inside the issuing-state slot must never be inflated.
        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() {
        // `fit_line1_length` only ever changes behavior on a short line
        // (`n.len() < target`); exact-width and too-long lines must be
        // byte-identical to `fit_length`, unconditionally. Lengths are
        // computed rather than hard-coded, so a miscounted literal fails
        // loudly instead of silently testing the wrong branch.
        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)
        );
    }
}