mrz 0.6.4

Zero-dependency 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
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
//! Candidate generation for MRZ lines damaged badly enough that characters are
//! *missing*, not merely misread.
//!
//! The check digits are the oracle everywhere in this crate; nothing here
//! decides what a character is. This module only widens the set of candidates
//! the oracle gets to rule on, and reports honestly when the oracle cannot
//! separate them.
//!
//! # The gap this closes
//!
//! [`crate::checksum`]'s existing length repair inserts missing characters in
//! exactly two places: inside the longest `<` filler run, or appended at the
//! end. That covers the common OCR failure — a truncated trailing filler run —
//! and nothing else. Two failures measured on real documents fall outside it:
//!
//! - A hole punched through an ID card's MRZ. `ocrs` **drops** the destroyed
//!   glyph rather than emitting a placeholder, so a TD1 line 2 arrives 29
//!   characters wide with the deficit in the middle of the expiry field.
//! - A finger over the start of a passport's line 2, arriving 42 characters
//!   wide with the deficit at the front.
//!
//! In both cases every candidate the old repair builds still has the data
//! shifted, so every check digit correctly rejects all of them, and a
//! recoverable document falls through to a non-deterministic fallback.
//! [`width_candidates`] restores the width by inserting [`UNKNOWN`] at *every*
//! position, and [`solve_field`] resolves those unknowns against the field's
//! own check digit.
//!
//! # What "resolved" is allowed to mean
//!
//! A check digit sees only the value of a field mod 10 (ICAO 9303 part 3
//! §4.9), so a single unknown position generally admits **four** characters —
//! one residue class from [`crate::CLASSES`]. On the punched ID card the four
//! are `3`, `D`, `N`, `X`. Three of them make the expiry field `D01230`,
//! `N01230`, `X01230`, which are not dates: [`FieldKind::Date`] prunes them
//! with [`crate::Date::is_well_formed`] and the recovery is unique.
//!
//! Where the arithmetic genuinely cannot separate the candidates —
//! the finger-occluded passport leaves 138 surviving pairs — the answer is
//! [`Resolution::Ambiguous`], never a pick. A guess that happens to be wrong
//! is worse than a refusal, because it is indistinguishable from a proof.
//!
//! # A third shape: correct width, one glyph wrong
//!
//! Neither of the above covers a line that arrived the *correct* width with
//! one glyph misread — no insertion or deletion, just OCR confusing e.g. `0`
//! and `O`. This looks like it should be *easier* than the missing-character
//! case, but the arithmetic makes it the more dangerous one to get sloppy
//! about: because the check-digit weights 7, 3, and 1 are each coprime to 10,
//! whether two characters are interchangeable at a position depends only on
//! their ICAO value mod 10, *never* on the weight — so a full residue class
//! (see [`crate::CLASSES`]) is check-digit-equivalent at every position, not
//! just some. `0`, `A`, `K`, and `U` all share value ≡ 0 (mod 10), so an
//! unrestricted single-position sweep of the whole alphabet would accept `A`
//! and `K` as readings of a misprinted `0` just as readily as the `O` a real
//! OCR engine would actually emit. [`substitution_candidates`] sweeps a
//! bounded, hand-built table of *visually* confusable characters instead of
//! the full alphabet, so [`solve_substitution`]'s answers stay restricted to
//! misreads OCR plausibly makes, not every character sharing a residue.

use crate::checksum::{fit_length, is_mrz_charset, verify};
use crate::dates::Date;

/// Marks a position the recognizer could not read. Deliberately **not** `<`:
/// the filler is a legitimate MRZ value (0), so reusing it would make "no
/// character here" indistinguishable from "the character here is a filler".
/// Outside the ICAO alphabet by design, so a string still carrying one can
/// never be mistaken for a parseable line.
pub const UNKNOWN: char = '?';

/// The 37-character ICAO 9303 MRZ alphabet, in the order the solver sweeps it.
pub const MRZ_ALPHABET: &str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ<";

/// Most [`UNKNOWN`] positions [`solve_field`] will sweep in one field.
///
/// Two is 37² = 1369 check-digit verifications — trivial — and three would be
/// 50653 candidates of which a useful fraction survive, i.e. an `Ambiguous`
/// answer so wide it carries no information. The bound exists for the same
/// reason [`crate::checksum`]'s defiller has one: this runs inside an OCR
/// retry loop, and an unbounded sweep there is a latency bug waiting for a
/// bad photo.
const MAX_UNKNOWNS: usize = 2;

/// Most characters [`width_candidates`] will insert. Past this the position
/// sweep stops being a repair and starts being a search over lines that were
/// never read in the first place.
const MAX_WIDTH_DEFICIT: usize = 2;

/// Which ICAO field a [`solve_field`] call is resolving. Selects the
/// structural constraint applied *after* the check digit, never instead of it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum FieldKind {
    /// Left-justified, `<`-padded (ICAO 9303 part 4 §4.2.2): a filler may only
    /// appear in the trailing run, so `B<98730<` is not a document number
    /// however well its check digit verifies.
    DocumentNumber,
    /// `YYMMDD`. Must be six digits naming a real calendar date.
    Date,
    /// Left-justified and `<`-padded like [`FieldKind::DocumentNumber`].
    PersonalNumber,
    /// No constraint beyond the check digit and the MRZ alphabet.
    Other,
}

/// What the check digit could prove about a field carrying [`UNKNOWN`]s.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Resolution {
    /// Exactly one reading satisfies the check digit and the field's
    /// structural constraint. This is a proof, not a preference.
    Unique(String),
    /// Several readings satisfy both and nothing in the MRZ can separate them
    /// — the check digit's blindspot, made explicit. Sorted, so the output is
    /// stable across runs.
    Ambiguous { candidates: Vec<String> },
    /// No reading satisfies the check digit, or the input was outside what
    /// this solver will attempt (too many unknowns, an unreadable check digit,
    /// non-ASCII input).
    Unresolvable,
}

impl Resolution {
    /// The proven reading, if there is exactly one. `Ambiguous` deliberately
    /// yields `None` — a caller that wants "the first candidate" has to reach
    /// into the variant and own that decision explicitly.
    pub fn unique(&self) -> Option<&str> {
        match self {
            Resolution::Unique(s) => Some(s.as_str()),
            _ => None,
        }
    }
}

/// Every way `line` could be restored to exactly `target` characters.
///
/// Combines the checksum module's existing filler-run and end-padding
/// candidates with a sweep that inserts [`UNKNOWN`] at each of the `len + 1`
/// positions — the case a punched hole or an occluded line start produces.
/// Candidates containing [`UNKNOWN`] are not parseable as they stand; resolve
/// them field-by-field with [`solve_field`] first.
///
/// Bounded and deterministic: at most `target + 4` candidates, each exactly
/// `target` characters, in a stable order. Returns empty for non-ASCII input
/// or a deficit wider than the module's insertion bound.
pub fn width_candidates(line: &str, target: usize) -> Vec<String> {
    let n: String = line.chars().filter(|c| !c.is_whitespace()).collect();
    if !n.is_ascii() || target == 0 {
        return Vec::new();
    }
    let mut out: Vec<String> = Vec::new();

    // The pre-existing behaviour first, so a line this module could already
    // handle keeps resolving through the same candidate it always did.
    for candidate in fit_length(&n, target) {
        push_unique(&mut out, candidate, target);
    }

    let len = n.len();
    if len < target {
        let deficit = target - len;
        if deficit <= MAX_WIDTH_DEFICIT {
            let bytes = n.as_bytes();
            for at in 0..=len {
                let mut s = String::with_capacity(target);
                s.push_str(&n[..at]);
                for _ in 0..deficit {
                    s.push(UNKNOWN);
                }
                s.push_str(&n[at..]);
                debug_assert_eq!(bytes.len() + deficit, s.len());
                push_unique(&mut out, s, target);
            }
        }
    }
    out
}

/// Append `candidate` if it is exactly `target` characters and not already
/// present — the de-duplication [`width_candidates`] needs because the
/// existing filler-run repair and the position sweep overlap whenever the
/// deficit happens to sit inside a filler run.
fn push_unique(out: &mut Vec<String>, candidate: String, target: usize) {
    if candidate.len() == target && !out.contains(&candidate) {
        out.push(candidate);
    }
}

/// Resolve the [`UNKNOWN`] positions in one check-digited field.
///
/// Sweeps [`MRZ_ALPHABET`] over every unknown position and keeps the readings
/// whose own check digit verifies *and* which satisfy `kind`'s structural
/// constraint. A field with no unknowns is simply verified.
///
/// Returns [`Resolution::Unresolvable`] rather than attempting a solve when
/// `check` is itself [`UNKNOWN`]: a check digit that was not read cannot prove
/// anything, and recomputing it from the candidate would only prove the
/// candidate agrees with itself.
pub fn solve_field(field: &str, check: char, kind: FieldKind) -> Resolution {
    if !field.is_ascii() || check == UNKNOWN {
        return Resolution::Unresolvable;
    }
    let chars: Vec<char> = field.chars().collect();
    let unknowns: Vec<usize> = chars
        .iter()
        .enumerate()
        .filter(|(_, c)| **c == UNKNOWN)
        .map(|(i, _)| i)
        .collect();
    if unknowns.len() > MAX_UNKNOWNS {
        return Resolution::Unresolvable;
    }
    // Anything that is neither a known MRZ character nor an explicit unknown
    // is corruption this module has no business guessing around.
    if chars
        .iter()
        .any(|c| *c != UNKNOWN && !is_mrz_charset(&c.to_string()))
    {
        return Resolution::Unresolvable;
    }

    let alphabet: Vec<char> = MRZ_ALPHABET.chars().collect();
    let mut hits: Vec<String> = Vec::new();
    let total = alphabet.len().pow(unknowns.len() as u32);
    for combo in 0..total {
        let mut candidate = chars.clone();
        let mut rest = combo;
        for &pos in &unknowns {
            candidate[pos] = alphabet[rest % alphabet.len()];
            rest /= alphabet.len();
        }
        let s: String = candidate.into_iter().collect();
        if verify(&s, check) && satisfies(&s, kind) {
            hits.push(s);
        }
    }

    hits.sort();
    match hits.len() {
        0 => Resolution::Unresolvable,
        1 => Resolution::Unique(hits.remove(0)),
        _ => Resolution::Ambiguous { candidates: hits },
    }
}

/// Positions [`substitution_candidates`] will change in one candidate.
///
/// Fixed at one by design, not merely by default: [`CONFUSABLES`] already
/// bounds each position to a handful of visually plausible alternatives, but
/// letting two positions vary independently multiplies those small counts
/// together and starts re-admitting the coincidental agreement the table
/// exists to keep out. A field with two misread glyphs is better served by
/// two separate passes — or by [`solve_field`] once the still-wrong position
/// is known — than by a search that quietly widens what "one repair" means.
const MAX_SUBSTITUTIONS: usize = 1;

/// Most candidates [`substitution_candidates`] will return.
///
/// A sibling of [`MAX_UNKNOWNS`]/[`MAX_WIDTH_DEFICIT`]: this runs inside the
/// same OCR retry loop, so the sweep — at most `field.len() * 4` candidates
/// given [`CONFUSABLES`]'s widest row — needs a hard ceiling rather than trust
/// that no field ever gets long enough to matter.
const MAX_SUBSTITUTION_CANDIDATES: usize = 256;

/// Bounded table of OCR glyph confusions, `(character, confusable-with)`.
///
/// Each entry is bidirectional: `('0', "ODQ")` means `0` may be misread as
/// `O`, `D`, or `Q` *and* that any of `O`, `D`, `Q` may be misread as `0` —
/// [`confusable_alternatives`] walks the table both ways, so the digit and
/// its lookalike letters do not each need their own row.
///
/// Deliberately small and shape-driven (round vs. round, vertical stroke vs.
/// vertical stroke), not derived from [`crate::CLASSES`]. A residue class is
/// check-digit-equivalent at *every* weight (see the module doc), but `K` and
/// `U` are not plausible misreads of `0` — restricting this table to glyphs
/// that actually look alike is what keeps [`solve_substitution`]'s answers
/// meaningfully unique instead of reproducing the whole residue class.
pub const CONFUSABLES: &[(char, &str)] = &[
    ('0', "ODQ"),
    ('1', "ILTU"),
    ('2', "Z"),
    ('4', "A"),
    ('5', "S"),
    ('6', "G"),
    ('7', "T"),
    ('8', "B"),
    ('9', "G"),
];

/// Every character [`CONFUSABLES`] lists as a plausible misread of `c`, in
/// both directions, excluding `c` itself.
fn confusable_alternatives(c: char) -> Vec<char> {
    let mut alts: Vec<char> = Vec::new();
    for &(key, group) in CONFUSABLES {
        if c == key {
            for g in group.chars() {
                if g != c && !alts.contains(&g) {
                    alts.push(g);
                }
            }
        } else if group.contains(c) && key != c && !alts.contains(&key) {
            alts.push(key);
        }
    }
    alts
}

/// Every single-glyph substitution of `field` under [`CONFUSABLES`].
///
/// Sweeps positions left to right; at each position, tries every plausible
/// confusable in place of the character actually there ([`MAX_SUBSTITUTIONS`]
/// keeps this to one changed position per candidate — never two at once).
/// Non-ASCII input or a field still carrying [`UNKNOWN`] yields nothing: a
/// position this module cannot read is [`solve_field`]'s problem, not this
/// one's. The identity reading (`field` itself, unchanged) is never included
/// — this function only proposes *different* readings for [`solve_substitution`]
/// to test. Bounded by [`MAX_SUBSTITUTION_CANDIDATES`], in a stable order.
pub fn substitution_candidates(field: &str) -> Vec<String> {
    if !field.is_ascii() || field.contains(UNKNOWN) {
        return Vec::new();
    }
    let chars: Vec<char> = field.chars().collect();
    let mut out: Vec<String> = Vec::new();
    'positions: for i in 0..chars.len() {
        for alt in confusable_alternatives(chars[i]) {
            let mut candidate = chars.clone();
            candidate[i] = alt;
            let s: String = candidate.into_iter().collect();
            debug_assert_eq!(
                s.chars().zip(field.chars()).filter(|(a, b)| a != b).count(),
                MAX_SUBSTITUTIONS,
                "substitution_candidates must change exactly one position"
            );
            if s != field && !out.contains(&s) {
                out.push(s);
                if out.len() >= MAX_SUBSTITUTION_CANDIDATES {
                    break 'positions;
                }
            }
        }
    }
    out
}

/// Resolve a field that is the *right width* but may carry one misread glyph.
///
/// A field that already verifies is returned unchanged — this never
/// "repairs" a field the check digit has already proven, only one it has
/// rejected. Otherwise sweeps [`substitution_candidates`], keeping readings
/// whose check digit verifies *and* which satisfy `kind`'s structural
/// constraint, exactly as [`solve_field`] does for [`UNKNOWN`] positions.
///
/// Returns [`Resolution::Unresolvable`] for non-ASCII input or an unreadable
/// check digit, for the same reason [`solve_field`] does: a check digit that
/// was not itself read faithfully cannot prove anything about the field next
/// to it.
pub fn solve_substitution(field: &str, check: char, kind: FieldKind) -> Resolution {
    if !field.is_ascii() || check == UNKNOWN {
        return Resolution::Unresolvable;
    }
    if verify(field, check) && satisfies(field, kind) {
        return Resolution::Unique(field.to_string());
    }

    let mut hits: Vec<String> = Vec::new();
    for candidate in substitution_candidates(field) {
        if verify(&candidate, check) && satisfies(&candidate, kind) && !hits.contains(&candidate) {
            hits.push(candidate);
        }
    }

    hits.sort();
    match hits.len() {
        0 => Resolution::Unresolvable,
        1 => Resolution::Unique(hits.remove(0)),
        _ => Resolution::Ambiguous { candidates: hits },
    }
}

/// Every concrete reading of a line still carrying [`UNKNOWN`]s, for callers
/// that would rather let a whole-record parse be the oracle than resolve field
/// by field.
///
/// Bounded by [`MAX_UNKNOWNS`] exactly as [`solve_field`] is — a line with more
/// unknowns than that yields nothing rather than a combinatorial expansion.
/// A line with no unknowns yields itself, so this is safe to call
/// unconditionally.
pub(crate) fn concrete_fillings(line: &str) -> Vec<String> {
    if !line.is_ascii() {
        return Vec::new();
    }
    let chars: Vec<char> = line.chars().collect();
    let unknowns: Vec<usize> = chars
        .iter()
        .enumerate()
        .filter(|(_, c)| **c == UNKNOWN)
        .map(|(i, _)| i)
        .collect();
    if unknowns.is_empty() {
        return vec![line.to_string()];
    }
    if unknowns.len() > MAX_UNKNOWNS {
        return Vec::new();
    }
    let alphabet: Vec<char> = MRZ_ALPHABET.chars().collect();
    let mut out = Vec::with_capacity(alphabet.len().pow(unknowns.len() as u32));
    for combo in 0..alphabet.len().pow(unknowns.len() as u32) {
        let mut candidate = chars.clone();
        let mut rest = combo;
        for &pos in &unknowns {
            candidate[pos] = alphabet[rest % alphabet.len()];
            rest /= alphabet.len();
        }
        out.push(candidate.into_iter().collect());
    }
    out
}

/// The structural constraint for `kind` — applied only to readings the check
/// digit has already accepted, so it can never rescue a value the arithmetic
/// rejected, only narrow a set the arithmetic could not separate.
fn satisfies(field: &str, kind: FieldKind) -> bool {
    match kind {
        FieldKind::Other => true,
        FieldKind::DocumentNumber | FieldKind::PersonalNumber => left_justified(field),
        FieldKind::Date => is_plausible_yymmdd(field),
    }
}

/// No `<` appears before a non-filler character: ICAO left-justifies these
/// fields and pads them on the right only.
fn left_justified(field: &str) -> bool {
    !field.trim_end_matches('<').contains('<')
}

/// Six digits naming a real calendar date.
///
/// The century is unknown at field level — the pivot lives in
/// [`crate::ParseOptions`] and belongs to the parser, not here — so a date is
/// accepted when it is well-formed under **either** century. That only matters
/// for `yy = 00` on 29 February (1900 is not a leap year, 2000 is), and
/// accepting the union is the conservative choice: this function's job is to
/// discard the impossible, never to narrow by guessing an era.
fn is_plausible_yymmdd(field: &str) -> bool {
    if field.len() != 6 || !field.bytes().all(|b| b.is_ascii_digit()) {
        return false;
    }
    let yy: i32 = field[0..2].parse().expect("two ascii digits");
    let month: u32 = field[2..4].parse().expect("two ascii digits");
    let day: u32 = field[4..6].parse().expect("two ascii digits");
    Date::new(1900 + yy, month, day).is_well_formed()
        || Date::new(2000 + yy, month, day).is_well_formed()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::checksum::check_digit;

    #[test]
    fn width_candidates_are_all_target_width_and_deduplicated() {
        for target in [30usize, 36, 44] {
            let short: String = "A".repeat(target - 1);
            let candidates = width_candidates(&short, target);
            assert!(!candidates.is_empty());
            for c in &candidates {
                assert_eq!(c.len(), target, "candidate {c:?} is not {target} wide");
            }
            let mut sorted = candidates.clone();
            sorted.sort();
            sorted.dedup();
            assert_eq!(sorted.len(), candidates.len(), "duplicate candidates");
        }
    }

    #[test]
    fn width_candidates_sweep_every_insertion_point() {
        // A deficit of one in a line with no filler run at all: the old
        // filler-run repair has nothing to inflate, so every candidate here
        // comes from the position sweep.
        let candidates = width_candidates("ABCDE", 6);
        assert!(candidates.contains(&"?ABCDE".to_string()));
        assert!(candidates.contains(&"AB?CDE".to_string()));
        assert!(candidates.contains(&"ABCDE?".to_string()));
    }

    #[test]
    fn width_candidates_refuses_a_deficit_it_cannot_bound() {
        let candidates = width_candidates("AB", 30);
        assert!(
            candidates.iter().all(|c| !c.contains(UNKNOWN)),
            "a 28-character deficit must not be swept position by position"
        );
    }

    #[test]
    fn a_field_with_no_unknowns_is_just_verified() {
        // ICAO 9303 part 3 worked example.
        assert_eq!(
            solve_field("L898902C<", '3', FieldKind::DocumentNumber),
            Resolution::Unique("L898902C<".to_string())
        );
        assert_eq!(
            solve_field("L898902C<", '4', FieldKind::DocumentNumber),
            Resolution::Unresolvable
        );
    }

    #[test]
    fn an_unreadable_check_digit_proves_nothing() {
        assert_eq!(
            solve_field("6908?22", UNKNOWN, FieldKind::Other),
            Resolution::Unresolvable
        );
    }

    #[test]
    fn too_many_unknowns_is_refused_not_attempted() {
        assert_eq!(
            solve_field("???????", '0', FieldKind::Other),
            Resolution::Unresolvable
        );
    }

    #[test]
    fn left_justified_rejects_an_interior_filler() {
        assert!(left_justified("B1987309"));
        assert!(left_justified("B198730<"));
        assert!(!left_justified("B<987309"));
    }

    #[test]
    fn plausible_dates_reject_impossible_calendars() {
        assert!(!is_plausible_yymmdd("890229")); // 1989/2089 both non-leap
        assert!(is_plausible_yymmdd("000229")); // 2000 is a leap year
        assert!(is_plausible_yymmdd("301230"));
        assert!(!is_plausible_yymmdd("301332"));
        assert!(!is_plausible_yymmdd("D01230"));
        assert!(!is_plausible_yymmdd("30123"));
    }

    #[test]
    fn confusable_alternatives_are_bidirectional_and_exclude_identity() {
        // '0' is a key row: its listed confusables come back directly.
        let mut zero = confusable_alternatives('0');
        zero.sort();
        assert_eq!(zero, vec!['D', 'O', 'Q']);
        // 'O' only appears inside '0's row, so it must resolve back to '0'
        // via the reverse direction, without needing its own row.
        assert_eq!(confusable_alternatives('O'), vec!['0']);
        // A character absent from every row has no confusables at all.
        assert!(confusable_alternatives('Y').is_empty());
    }

    #[test]
    fn substitution_candidates_never_includes_the_identity_reading() {
        for field in ["13E1AE", "AB0234C7", "L898902C", "OOOOOO"] {
            let candidates = substitution_candidates(field);
            assert!(
                !candidates.contains(&field.to_string()),
                "{field:?} candidates must never include the unchanged input"
            );
        }
    }

    #[test]
    fn substitution_candidates_respects_the_cap_on_a_worst_case_input() {
        // '1' is CONFUSABLES's widest row (I, L, T, U — four alternatives),
        // so a long run of '1's is the worst case for the sweep: 100
        // positions * 4 alternatives = 400 raw candidates, well past the cap.
        let field = "1".repeat(100);
        let candidates = substitution_candidates(&field);
        assert_eq!(candidates.len(), MAX_SUBSTITUTION_CANDIDATES);
    }

    #[test]
    fn solve_substitution_leaves_an_already_verifying_field_unchanged() {
        // ICAO 9303 part 3 worked example, reused from `solve_field`'s test:
        // a field that already checksums must never be "repaired".
        assert_eq!(
            solve_substitution("L898902C<", '3', FieldKind::DocumentNumber),
            Resolution::Unique("L898902C<".to_string())
        );
    }

    #[test]
    fn solve_substitution_resolves_a_single_confusable_glyph() {
        // Synthetic field, not drawn from any real document: the printed
        // field is "13E1AE" (check digit computed via `checksum::check_digit`
        // the same way an issuer's MRZ would be), and OCR misreads the
        // leading '1' as the visually similar 'I' — a `CONFUSABLES` pair.
        let field = "13E1AE";
        let check = '1';
        assert_eq!(check_digit(field).unwrap(), 1, "fixture's own check digit");
        let corrupted = "I3E1AE";
        assert!(
            !verify(corrupted, check),
            "the OCR misread must not verify as-is"
        );
        assert_eq!(
            solve_substitution(corrupted, check, FieldKind::Other),
            Resolution::Unique(field.to_string())
        );
    }

    #[test]
    fn solve_substitution_reports_ambiguity_instead_of_guessing() {
        // Synthetic field: two different single-glyph substitutions of this
        // corrupted reading both verify against the same check digit, and
        // neither the checksum nor `FieldKind::Other` can separate them. This
        // is exactly why `CONFUSABLES` must stay a bounded, shape-driven
        // table rather than a full residue-class sweep (see the module
        // doc): even restricted to plausible OCR confusions, ambiguity is
        // still possible — an unrestricted sweep over `CLASSES` would only
        // make it worse by admitting readings like 'K' or 'U' here too.
        let corrupted = "O0ZVEZ";
        let check = '9';
        assert!(!verify(corrupted, check));
        assert_eq!(
            solve_substitution(corrupted, check, FieldKind::Other),
            Resolution::Ambiguous {
                candidates: vec!["00ZVEZ".to_string(), "OOZVEZ".to_string()],
            }
        );
    }
}