mrz 0.6.2

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
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! MRZ emission for all five ICAO 9303 formats — the deterministic inverse of
//! [`crate::parse_td3`], [`crate::parse_td2`], [`crate::parse_td1`],
//! [`crate::parse_mrv_a`], and [`crate::parse_mrv_b`].
//!
//! Given structured field values, [`format_td3`], [`format_td2`],
//! [`format_td1`], [`format_mrv_a`], and [`format_mrv_b`] produce the
//! ICAO-specified lines with every check digit computed via the same
//! [`crate::check_digit`] math the parsers verify against. Feeding the output
//! back through the matching `parse_*` function always yields a record with
//! `valid() == true`.
//!
//! Field widths and offsets mirror the parsers exactly:
//! - **TD3** (two 44-char lines): document code (2) + issuing country (3) +
//!   name field (39) on line 1; document number (9) + check (1) +
//!   nationality (3) + date of birth (6) + check (1) + sex (1) + date of
//!   expiry (6) + check (1) + personal number (14) + check (1) + composite
//!   check (1) on line 2.
//! - **TD2** (two 36-char lines): document code (2) + issuing country (3) +
//!   name field (31) on line 1; document number (9) + check (1) +
//!   nationality (3) + date of birth (6) + check (1) + sex (1) + date of
//!   expiry (6) + check (1) + optional data (7) + composite check (1) on
//!   line 2. TD2 has no separate check digit over the optional-data field.
//! - **TD1** (three 30-char lines): document code (2) + issuing country (3) +
//!   document number (9) + check (1) + optional data 1 (15) on line 1; date
//!   of birth (6) + check (1) + sex (1) + date of expiry (6) + check (1) +
//!   nationality (3) + optional data 2 (11) + composite check (1) on line 2;
//!   name field (30) on line 3. TD1 has no separate check digit over either
//!   optional-data field.
//! - **MRV-A** (two 44-char lines): document code (2, `"V"`) + issuing country
//!   (3) + name field (39) on line 1; document number (9) + check (1) +
//!   nationality (3) + date of birth (6) + check (1) + sex (1) + date of
//!   expiry (6) + check (1) + optional data (16) on line 2. No personal-number
//!   check digit and no composite check digit — MRVs don't have one.
//! - **MRV-B** (two 36-char lines): document code (2, `"V"`) + issuing country
//!   (3) + name field (31) on line 1; document number (9) + check (1) +
//!   nationality (3) + date of birth (6) + check (1) + sex (1) + date of
//!   expiry (6) + check (1) + optional data (8) on line 2. Same as MRV-A: no
//!   personal-number check digit, no composite check digit.
//!
//! Input fields are taken in MRZ-native form (`YYMMDD` dates, uppercase
//! `[A-Z0-9]`) rather than the parser's output form (ISO dates, spaced given
//! names) — this keeps emission lossless and deterministic instead of forcing
//! a fragile un-parse of the parser's normalized/century-inferred output.
//! Any character outside `[A-Z0-9]` (including spaces between given names) is
//! mapped to the filler `<`, and every fixed-width field is padded with `<`
//! or truncated to its exact width — this function never panics and always
//! returns exactly 44+1+44 = 89 characters.
//!
//! The `surname`/`given_names` pair feeding the name field is the one
//! exception to the blanket "non-alphanumeric maps to filler" rule above:
//! ICAO 9303 Part 3 §4.6 defines punctuation-specific handling for names
//! (`knowledge/docs9303/Doc_9303_Part3_Specs_Common_to_all_MRTDs.md:509-535`)
//! that an apostrophe is dropped with no filler, not mapped to one — see
//! [`clean_name_half`] for the full rule set. Every other field
//! (`document_number`, `personal_number`/`optional_data`) keeps the blanket
//! [`clean`] behavior, per that same Part 3 passage read together with
//! `Doc_9303_Part4_Specs_for_MRPs_and_TD3_MRTDs.md:415`, which specifies
//! those fields as flat alphanumeric-or-filler, with no name-style
//! punctuation carve-out.

use crate::checksum::check_digit;
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};

/// Raw TD3 sub-fields, in MRZ-native form (see module docs).
///
/// `document_number` and `personal_number` are limited to 9 and 14 characters
/// respectively (the field widths); longer input is silently truncated.
/// `date_of_birth` / `date_of_expiry` are `YYMMDD`, not ISO dates.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Td3Fields {
    /// Document code, e.g. `"P"` for passport. Defaults to `"P"`.
    pub document_code: String,
    /// Issuing state (3-letter ICAO code).
    pub issuing_country: String,
    /// Document number, up to 9 characters.
    pub document_number: String,
    pub surname: String,
    pub given_names: String,
    /// Nationality (3-letter ICAO code).
    pub nationality: String,
    /// Date of birth as `YYMMDD`.
    pub date_of_birth: String,
    /// `"M"`, `"F"`, or `"X"` (unspecified — emitted as the filler `<`).
    pub sex: String,
    /// Date of expiry as `YYMMDD`.
    pub date_of_expiry: String,
    /// Optional personal number, up to 14 characters.
    pub personal_number: Option<String>,
}

impl Default for Td3Fields {
    fn default() -> Self {
        Self {
            document_code: "P".to_string(),
            issuing_country: String::new(),
            document_number: String::new(),
            surname: String::new(),
            given_names: String::new(),
            nationality: String::new(),
            date_of_birth: String::new(),
            sex: String::new(),
            date_of_expiry: String::new(),
            personal_number: None,
        }
    }
}

/// Map any character outside `[A-Z0-9]` (after uppercasing) to the filler `<`.
fn clean(s: &str) -> String {
    s.chars()
        .map(|c| {
            let u = c.to_ascii_uppercase();
            if u.is_ascii_alphanumeric() {
                u
            } else {
                '<'
            }
        })
        .collect()
}

/// Clean and pad/truncate `s` to exactly `width` characters using `<` filler.
fn field(s: &str, width: usize) -> String {
    let cleaned = clean(s);
    let mut chars = cleaned.chars();
    let mut out = String::with_capacity(width);
    for _ in 0..width {
        out.push(chars.next().unwrap_or('<'));
    }
    out
}

/// Clean one half (primary or secondary identifier) of a name field per
/// ICAO 9303 Part 3 §4.6
/// (`knowledge/docs9303/Doc_9303_Part3_Specs_Common_to_all_MRTDs.md:509-535`).
/// Unlike [`clean`], this does **not** map every non-alphanumeric character
/// to the filler `<` — names get their own punctuation rules:
///
/// - Each character is first uppercased via `char::to_uppercase()` (not
///   `to_ascii_uppercase`), then, for **each** resulting char `u` (usually
///   one, but see `ß`→`SS` below):
///   1. if `u` is a Table A national character (Part 3 §6,
///      `:703-807`), it is replaced by its [`TransliterationStyle::Expanded`]
///      transliteration — e.g. `Ü`→`UE`, `Ñ`→`N` — with **no** separator
///      pushed around it. This is the transliteration Part 3 `:493` mandates
///      ("The issuing State or organization shall transliterate national
///      characters using only the allowed OCR-B characters") and fixes what
///      was previously silent data loss: `MÜLLER` used to emit as `MLLER`,
///      now `MUELLER`.
///   2. else if `u` is `A`-`Z` or `0`-`9`, it is kept as-is.
///   3. else the existing punctuation rules below apply to `u`.
/// - Hyphen (`:517-521`), comma (`:523-532`), and whitespace each become a
///   single separator filler `<`.
/// - **Apostrophe is dropped entirely, with no filler in its place**
///   (`:511-515`) — e.g. `O'CONNOR` becomes `OCONNOR`, not `O<CONNOR`. This
///   is the one rule the crate got wrong before this function existed.
/// - Every other punctuation character is likewise dropped entirely, with
///   no filler (`:534-535`).
/// - `0`-`9` is kept as-is. Part 3 §4.6 (`:507`) states plainly that
///   "numeric characters shall not be used in the name fields of the MRZ",
///   but — unlike the apostrophe/hyphen/comma cases above — it defines no
///   mapping for one that shows up anyway. Silently rewriting a digit to a
///   filler would erase information with no textual basis in the spec, so
///   this function instead preserves digits verbatim, matching the
///   "alphanumeric survives untouched" behavior [`clean`] already applies
///   to the document-number and optional-data fields. A digit reaching this
///   function means the caller handed it a name that isn't spec-clean;
///   per CLAUDE.md's OCR philosophy ("every field should be validated"),
///   that validation belongs upstream of emission, not inside it.
///
/// After the per-character pass, consecutive separators collapse to one and
/// leading/trailing separators are trimmed. That collapse is what makes
/// `"ANNA, MARIA"` (a comma *immediately followed by* a space) yield
/// `ANNA<MARIA` rather than `ANNA<<MARIA`, matching
/// `Doc_9303_Part3_Specs_Common_to_all_MRTDs.md:531-532`'s worked example.
fn clean_name_half(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut last_was_sep = false;
    for c in s.chars() {
        for u in c.to_uppercase() {
            if let Some(t) = crate::translit::transliterate_char(
                u,
                crate::translit::TransliterationStyle::Expanded,
            ) {
                out.push_str(t);
                last_was_sep = false;
            } else if u.is_ascii_alphanumeric() {
                out.push(u);
                last_was_sep = false;
            } else if u == '\'' {
                // Apostrophe: dropped, no filler (:511-515). `last_was_sep`
                // is deliberately left unchanged — an apostrophe is
                // transparent to separator collapsing on either side of it.
            } else if (u == '-' || u == ',' || u.is_whitespace()) && !last_was_sep {
                out.push('<');
                last_was_sep = true;
            }
            // Every other punctuation character: dropped, no filler (:534-535).
        }
    }
    // Trim leading/trailing separators left over from a name starting or
    // ending on a hyphen/comma/space (e.g. a stray leading space).
    out.trim_matches('<').to_string()
}

/// Truncate the `primary`/`secondary` name-field components (already run
/// through [`clean_name_half`]) to fit exactly `width` characters, when
/// their combined length exceeds it.
///
/// ICAO 9303 Part 4 §4.2.3 (`Doc_9303_Part4_Specs_for_MRPs_and_TD3_MRTDs.md:463-587`)
/// documents *several* issuer-discretionary truncation strategies —
/// truncating trailing components to initials, truncating components to a
/// shorter fixed length, or (this function's choice) dropping whole
/// components from the end and, if needed, cutting the last one short. Part
/// 4 does not prefer any one of these; there is no single "the" ICAO
/// truncation algorithm, so this is one conformant choice among several,
/// not a canonical behavior.
///
/// What Part 4 *does* make normative (`:465`, `:467`) is:
/// - a name that fits within `width` is never truncated — callers only
///   reach this function when it does not fit;
/// - when truncation happens, the **last character of the name field**
///   must be alphabetic `A`-`Z`, as the reader's only signal that
///   truncation occurred.
///
/// This function guarantees the second rule by construction: it assembles
/// whole `<`-or-`<<`-separated components until the next one would overflow
/// `width`, then — since every component is letters-only (guaranteed by
/// [`clean_name_half`]) — either takes a letters-only prefix of that next
/// component to land exactly on `width`, or (if there is no room left even
/// for the separator that would precede it) borrows straight from the next
/// component's letters instead of emitting a separator nothing follows.
/// Either way the character written last is always a letter, and the
/// returned string is always exactly `width` characters (as long as
/// `primary`/`secondary` together contain at least `width` characters,
/// which holds whenever this function is called, since it's only invoked
/// when the combined length exceeds `width`).
///
/// `Doc_9303_Part4_Specs_for_MRPs_and_TD3_MRTDs.md:585-587` documents that
/// this ambiguity runs both ways:
/// a name that happens to fill the field exactly, with no truncation at
/// all, is indistinguishable from a truncated one by the same rule — "this
/// name has not been truncated but it must be assumed that it has been
/// truncated". That is spec-documented ambiguity to design around, not a
/// bug to fix later; ICAO's own `PAPANDROPOULOUS` example
/// (`Doc_9303_Part4_Specs_for_MRPs_and_TD3_MRTDs.md:584`) is exactly this
/// case, and is pinned as a non-truncating golden vector in
/// `tests/icao_vectors.rs` for that reason.
fn truncate_name_components(primary: &str, secondary: &str, width: usize) -> String {
    // (separator-before, component) pairs, in emission order. The very
    // first component (if any) has an empty separator; primary/primary and
    // secondary/secondary components are joined by `<`; primary/secondary
    // is joined by `<<`.
    let mut parts: Vec<(&str, &str)> = Vec::new();
    let mut primary_components = primary.split('<').filter(|c| !c.is_empty());
    if let Some(first) = primary_components.next() {
        parts.push(("", first));
    }
    for component in primary_components {
        parts.push(("<", component));
    }
    let mut secondary_components = secondary.split('<').filter(|c| !c.is_empty());
    if let Some(first) = secondary_components.next() {
        parts.push(("<<", first));
    }
    for component in secondary_components {
        parts.push(("<", component));
    }

    let mut out = String::with_capacity(width);
    for (separator, component) in parts {
        let remaining = width.saturating_sub(out.len());
        if remaining == 0 {
            break;
        }
        let full_len = separator.len() + component.len();
        if full_len <= remaining {
            out.push_str(separator);
            out.push_str(component);
            continue;
        }
        // This component doesn't fit whole. Prefer letters over a
        // separator that nothing would follow, so the field always ends on
        // an alphabetic character:
        if separator.len() < remaining {
            out.push_str(separator);
            let take = remaining - separator.len();
            out.push_str(&component[..take]);
        } else {
            // Not even room for the separator — borrow straight from this
            // component's letters instead.
            let take = remaining.min(component.len());
            out.push_str(&component[..take]);
        }
        break;
    }
    out
}

/// Build the name field: `SURNAME<<GIVEN<NAMES`, padded/truncated to
/// `width`. Each half is cleaned independently by [`clean_name_half`] per
/// ICAO 9303 Part 3 §4.6 before joining — see that function's doc comment
/// for the punctuation rules — and, when the combined result overflows
/// `width`, [`truncate_name_components`] applies this crate's truncation
/// strategy (documented there).
fn name_field(surname: &str, given_names: &str, width: usize) -> String {
    let primary = clean_name_half(surname);
    let secondary = clean_name_half(given_names);
    // `format!("{p}<<")` then padding with fillers is byte-identical to
    // padding `p` alone when `secondary` is empty (both just place `<` in
    // every position after `p`), so the empty-secondary case needs no
    // special-casing here.
    let combined = format!("{primary}<<{secondary}");
    if combined.len() <= width {
        // `field` re-cleans its input via `clean`, but `combined` already
        // contains only `[A-Z0-9<]`, on which `clean` is a no-op — so this
        // is purely padding/truncation to `width`, not a second cleaning
        // pass with different rules.
        return field(&combined, width);
    }
    let truncated = truncate_name_components(&primary, &secondary, width);
    field(&truncated, width)
}

/// The 9-character document-number field, its check-digit character, and any
/// prefix the overflow encoding forces onto the optional-data field.
struct DocNumber {
    field: String,
    check: char,
    /// Overflow prefix for the optional field: `remainder + check digit + '<'`.
    /// Empty when the number fits its 9 characters.
    optional_prefix: String,
}

/// Encode a document number, using the ICAO 9303 Part 5 note j / Part 6 note j
/// long-document-number overflow form when it exceeds 9 characters and the
/// remainder fits `optional_width`. Part 4 defines no such rule for TD3 —
/// applying it there is a deliberate extension by analogy; see
/// `parser::read_overflow`'s doc comment for the full citation.
///
/// The overflow form prints all nine principal characters, sets the
/// check-digit position to a filler (instead of a check digit, per Part 5
/// note j / §4.2.4) to signal a truncated number, and writes
/// `remainder + check digit over the whole number + a terminating filler` at
/// the start of the optional field. The check digit is computed over the nine
/// principal characters concatenated with the remainder — i.e. `cleaned`
/// itself. If the remainder cannot fit, the number is truncated to 9 as
/// before — this function never produces an over-long field.
fn doc_number(number: &str, optional_width: usize) -> DocNumber {
    let cleaned = clean(number);
    let remainder_len = cleaned.len().saturating_sub(9);
    if cleaned.len() > 9 && remainder_len + 2 <= optional_width {
        let check = digit_char(&cleaned);
        return DocNumber {
            field: cleaned[0..9].to_string(),
            check: '<',
            optional_prefix: format!("{}{check}<", &cleaned[9..]),
        };
    }
    let field = field(&cleaned, 9);
    DocNumber {
        check: digit_char(&field),
        field,
        optional_prefix: String::new(),
    }
}

fn digit_char(field: &str) -> char {
    // `field` is always built from `clean`/`field`, i.e. only `[A-Z0-9<]`,
    // so `check_digit` can never fail here.
    char::from_digit(check_digit(field).expect("MRZ-charset field"), 10).expect("0-9")
}

/// Emit a TD3 (passport) MRZ: two 44-character lines joined by `\n`.
///
/// All four field check digits and the composite check digit are computed
/// from `fields` — the result always round-trips through
/// [`crate::parse_td3`] with `valid() == true` (see `tests/roundtrip.rs`).
pub fn format_td3(fields: &Td3Fields) -> String {
    let doc_code = field(&fields.document_code, 2);
    let issuing = field(&fields.issuing_country, 3);
    let name = name_field(&fields.surname, &fields.given_names, 39);
    let line1 = format!("{doc_code}{issuing}{name}");

    let DocNumber {
        field: doc_num,
        check: doc_num_check,
        optional_prefix,
    } = doc_number(&fields.document_number, 14);
    let nationality = field(&fields.nationality, 3);
    let dob = field(&fields.date_of_birth, 6);
    let dob_check = digit_char(&dob);
    let sex = match fields.sex.to_ascii_uppercase().as_str() {
        "M" => 'M',
        "F" => 'F',
        _ => '<',
    };
    let expiry = field(&fields.date_of_expiry, 6);
    let expiry_check = digit_char(&expiry);
    let personal = field(
        &format!(
            "{optional_prefix}{}",
            clean(fields.personal_number.as_deref().unwrap_or(""))
        ),
        14,
    );
    let personal_check = digit_char(&personal);

    // 43 chars: everything except the composite digit itself, in the same
    // layout `parser::parse_td3` expects (offsets 0..43).
    let line2_body = format!(
        "{doc_num}{doc_num_check}{nationality}{dob}{dob_check}{sex}{expiry}{expiry_check}{personal}{personal_check}"
    );
    debug_assert_eq!(line2_body.len(), 43);

    // Composite: line2[0..10] (doc number + check) + line2[13..20]
    // (DOB + check) + line2[21..43] (expiry + check + personal + check) —
    // mirrors `parser::parse_td3`'s `checks.composite` computation exactly.
    let composite_input = format!(
        "{}{}{}",
        &line2_body[0..10],
        &line2_body[13..20],
        &line2_body[21..43]
    );
    let composite_check = digit_char(&composite_input);

    let line2 = format!("{line2_body}{composite_check}");
    debug_assert_eq!(line1.len(), 44);
    debug_assert_eq!(line2.len(), 44);

    format!("{line1}\n{line2}")
}

/// Raw TD2 sub-fields, in MRZ-native form (see module docs).
///
/// `document_number` is limited to 9 characters (the field width); longer
/// input is silently truncated. `date_of_birth` / `date_of_expiry` are
/// `YYMMDD`, not ISO dates.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Td2Fields {
    /// Document code, e.g. `"I"` for identity card. Defaults to `"I"`.
    pub document_code: String,
    /// Issuing state (3-letter ICAO code).
    pub issuing_country: String,
    /// Document number, up to 9 characters.
    pub document_number: String,
    pub surname: String,
    pub given_names: String,
    /// Nationality (3-letter ICAO code).
    pub nationality: String,
    /// Date of birth as `YYMMDD`.
    pub date_of_birth: String,
    /// `"M"`, `"F"`, or `"X"` (unspecified — emitted as the filler `<`).
    pub sex: String,
    /// Date of expiry as `YYMMDD`.
    pub date_of_expiry: String,
    /// Optional data, up to 7 characters. TD2 has no check digit over this
    /// field on its own — it only feeds the composite check.
    pub optional_data: Option<String>,
}

impl Default for Td2Fields {
    fn default() -> Self {
        Self {
            document_code: "I".to_string(),
            issuing_country: String::new(),
            document_number: String::new(),
            surname: String::new(),
            given_names: String::new(),
            nationality: String::new(),
            date_of_birth: String::new(),
            sex: String::new(),
            date_of_expiry: String::new(),
            optional_data: None,
        }
    }
}

/// Emit a TD2 (identity-card) MRZ: two 36-character lines joined by `\n`.
///
/// The document number, date-of-birth, date-of-expiry, and composite check
/// digits are computed from `fields` — the result always round-trips through
/// [`crate::parse_td2`] with `valid() == true` (see `tests/roundtrip.rs`).
/// TD2 has no separate check digit over the optional-data field.
pub fn format_td2(fields: &Td2Fields) -> String {
    let doc_code = field(&fields.document_code, 2);
    let issuing = field(&fields.issuing_country, 3);
    let name = name_field(&fields.surname, &fields.given_names, 31);
    let line1 = format!("{doc_code}{issuing}{name}");
    debug_assert_eq!(line1.len(), 36);

    let DocNumber {
        field: doc_num,
        check: doc_num_check,
        optional_prefix,
    } = doc_number(&fields.document_number, 7);
    let nationality = field(&fields.nationality, 3);
    let dob = field(&fields.date_of_birth, 6);
    let dob_check = digit_char(&dob);
    let sex = match fields.sex.to_ascii_uppercase().as_str() {
        "M" => 'M',
        "F" => 'F',
        _ => '<',
    };
    let expiry = field(&fields.date_of_expiry, 6);
    let expiry_check = digit_char(&expiry);
    let optional = field(
        &format!(
            "{optional_prefix}{}",
            clean(fields.optional_data.as_deref().unwrap_or(""))
        ),
        7,
    );

    // 35 chars: everything except the composite digit itself, in the same
    // layout `parser::parse_td2` expects (offsets 0..35).
    let line2_body = format!(
        "{doc_num}{doc_num_check}{nationality}{dob}{dob_check}{sex}{expiry}{expiry_check}{optional}"
    );
    debug_assert_eq!(line2_body.len(), 35);

    // Composite: line2[0..10] (doc number + check) + line2[13..20]
    // (DOB + check) + line2[21..35] (expiry + check + optional data) —
    // mirrors `parser::parse_td2`'s `checks.composite` computation exactly.
    let composite_input = format!(
        "{}{}{}",
        &line2_body[0..10],
        &line2_body[13..20],
        &line2_body[21..35]
    );
    let composite_check = digit_char(&composite_input);

    let line2 = format!("{line2_body}{composite_check}");
    debug_assert_eq!(line2.len(), 36);

    format!("{line1}\n{line2}")
}

/// Raw TD1 sub-fields, in MRZ-native form (see module docs).
///
/// `document_number` is limited to 9 characters (the field width); longer
/// input is silently truncated. `date_of_birth` / `date_of_expiry` are
/// `YYMMDD`, not ISO dates.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct Td1Fields {
    /// Document code, e.g. `"I"` for identity card. Defaults to `"I"`.
    pub document_code: String,
    /// Issuing state (3-letter ICAO code).
    pub issuing_country: String,
    /// Document number, up to 9 characters.
    pub document_number: String,
    /// Optional data on line 1, up to 15 characters. TD1 has no separate
    /// check digit over this field on its own — it only feeds the composite.
    pub optional_data_1: Option<String>,
    pub surname: String,
    pub given_names: String,
    /// Nationality (3-letter ICAO code).
    pub nationality: String,
    /// Date of birth as `YYMMDD`.
    pub date_of_birth: String,
    /// `"M"`, `"F"`, or `"X"` (unspecified — emitted as the filler `<`).
    pub sex: String,
    /// Date of expiry as `YYMMDD`.
    pub date_of_expiry: String,
    /// Optional data on line 2, up to 11 characters. TD1 has no separate
    /// check digit over this field on its own — it only feeds the composite.
    pub optional_data_2: Option<String>,
}

impl Default for Td1Fields {
    fn default() -> Self {
        Self {
            document_code: "I".to_string(),
            issuing_country: String::new(),
            document_number: String::new(),
            optional_data_1: None,
            surname: String::new(),
            given_names: String::new(),
            nationality: String::new(),
            date_of_birth: String::new(),
            sex: String::new(),
            date_of_expiry: String::new(),
            optional_data_2: None,
        }
    }
}

/// Emit a TD1 (ID-card) MRZ: three 30-character lines joined by `\n`.
///
/// The document number, date-of-birth, date-of-expiry, and composite check
/// digits are computed from `fields` — the result always round-trips through
/// [`crate::parse_td1`] with `valid() == true` (see `tests/roundtrip.rs`).
/// TD1 has no separate check digit over either optional-data field.
pub fn format_td1(fields: &Td1Fields) -> String {
    let doc_code = field(&fields.document_code, 2);
    let issuing = field(&fields.issuing_country, 3);
    let DocNumber {
        field: doc_num,
        check: doc_num_check,
        optional_prefix,
    } = doc_number(&fields.document_number, 15);
    let optional1 = field(
        &format!(
            "{optional_prefix}{}",
            clean(fields.optional_data_1.as_deref().unwrap_or(""))
        ),
        15,
    );
    let line1 = format!("{doc_code}{issuing}{doc_num}{doc_num_check}{optional1}");
    debug_assert_eq!(line1.len(), 30);

    let dob = field(&fields.date_of_birth, 6);
    let dob_check = digit_char(&dob);
    let sex = match fields.sex.to_ascii_uppercase().as_str() {
        "M" => 'M',
        "F" => 'F',
        _ => '<',
    };
    let expiry = field(&fields.date_of_expiry, 6);
    let expiry_check = digit_char(&expiry);
    let nationality = field(&fields.nationality, 3);
    let optional2 = field(fields.optional_data_2.as_deref().unwrap_or(""), 11);

    // 29 chars: everything except the composite digit itself, in the same
    // layout `parser::parse_td1` expects (offsets 0..29).
    let line2_body = format!("{dob}{dob_check}{sex}{expiry}{expiry_check}{nationality}{optional2}");
    debug_assert_eq!(line2_body.len(), 29);

    // Composite: line1[5..30] (doc number + check + optional-1) +
    // line2[0..7] (DOB + check) + line2[8..15] (expiry + check) +
    // line2[18..29] (optional-2) — mirrors `parser::parse_td1`'s
    // `checks.composite` computation exactly.
    let composite_input = format!(
        "{}{}{}{}",
        &line1[5..30],
        &line2_body[0..7],
        &line2_body[8..15],
        &line2_body[18..29]
    );
    let composite_check = digit_char(&composite_input);

    let line2 = format!("{line2_body}{composite_check}");
    debug_assert_eq!(line2.len(), 30);

    let line3 = name_field(&fields.surname, &fields.given_names, 30);
    debug_assert_eq!(line3.len(), 30);

    format!("{line1}\n{line2}\n{line3}")
}

/// Raw MRV-A sub-fields, in MRZ-native form (see module docs).
///
/// `document_number` is limited to 9 characters (the field width); longer
/// input is silently truncated. `date_of_birth` / `date_of_expiry` are
/// `YYMMDD`, not ISO dates. MRV-A has no personal-number or composite check
/// digit — `optional_data` is free-form data up to 16 characters.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MrvAFields {
    /// Document code, always `"V"` for a visa. Defaults to `"V"`.
    pub document_code: String,
    /// Issuing state (3-letter ICAO code).
    pub issuing_country: String,
    /// Document number, up to 9 characters.
    pub document_number: String,
    pub surname: String,
    pub given_names: String,
    /// Nationality (3-letter ICAO code).
    pub nationality: String,
    /// Date of birth as `YYMMDD`.
    pub date_of_birth: String,
    /// `"M"`, `"F"`, or `"X"` (unspecified — emitted as the filler `<`).
    pub sex: String,
    /// Date of expiry as `YYMMDD`.
    pub date_of_expiry: String,
    /// Optional free-form data, up to 16 characters. No check digit covers
    /// this field — MRVs have neither a personal-number nor composite check.
    pub optional_data: Option<String>,
}

impl Default for MrvAFields {
    fn default() -> Self {
        Self {
            document_code: "V".to_string(),
            issuing_country: String::new(),
            document_number: String::new(),
            surname: String::new(),
            given_names: String::new(),
            nationality: String::new(),
            date_of_birth: String::new(),
            sex: String::new(),
            date_of_expiry: String::new(),
            optional_data: None,
        }
    }
}

/// Emit an MRV-A (machine readable visa) MRZ: two 44-character lines joined
/// by `\n`.
///
/// The document number, date-of-birth, and date-of-expiry check digits are
/// computed from `fields` — the result always round-trips through
/// [`crate::parse_mrv_a`] with `valid() == true` (see `tests/roundtrip.rs`).
/// MRV-A has no personal-number check digit and no composite check digit.
pub fn format_mrv_a(fields: &MrvAFields) -> String {
    let doc_code = field(&fields.document_code, 2);
    let issuing = field(&fields.issuing_country, 3);
    let name = name_field(&fields.surname, &fields.given_names, 39);
    let line1 = format!("{doc_code}{issuing}{name}");
    debug_assert_eq!(line1.len(), 44);

    let doc_num = field(&fields.document_number, 9);
    let doc_num_check = digit_char(&doc_num);
    let nationality = field(&fields.nationality, 3);
    let dob = field(&fields.date_of_birth, 6);
    let dob_check = digit_char(&dob);
    let sex = match fields.sex.to_ascii_uppercase().as_str() {
        "M" => 'M',
        "F" => 'F',
        _ => '<',
    };
    let expiry = field(&fields.date_of_expiry, 6);
    let expiry_check = digit_char(&expiry);
    let optional = field(fields.optional_data.as_deref().unwrap_or(""), 16);

    let line2 = format!(
        "{doc_num}{doc_num_check}{nationality}{dob}{dob_check}{sex}{expiry}{expiry_check}{optional}"
    );
    debug_assert_eq!(line2.len(), 44);

    format!("{line1}\n{line2}")
}

/// Raw MRV-B sub-fields, in MRZ-native form (see module docs).
///
/// `document_number` is limited to 9 characters (the field width); longer
/// input is silently truncated. `date_of_birth` / `date_of_expiry` are
/// `YYMMDD`, not ISO dates. MRV-B has no personal-number or composite check
/// digit — `optional_data` is free-form data up to 8 characters.
#[derive(Debug, Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub struct MrvBFields {
    /// Document code, always `"V"` for a visa. Defaults to `"V"`.
    pub document_code: String,
    /// Issuing state (3-letter ICAO code).
    pub issuing_country: String,
    /// Document number, up to 9 characters.
    pub document_number: String,
    pub surname: String,
    pub given_names: String,
    /// Nationality (3-letter ICAO code).
    pub nationality: String,
    /// Date of birth as `YYMMDD`.
    pub date_of_birth: String,
    /// `"M"`, `"F"`, or `"X"` (unspecified — emitted as the filler `<`).
    pub sex: String,
    /// Date of expiry as `YYMMDD`.
    pub date_of_expiry: String,
    /// Optional free-form data, up to 8 characters. No check digit covers
    /// this field — MRVs have neither a personal-number nor composite check.
    pub optional_data: Option<String>,
}

impl Default for MrvBFields {
    fn default() -> Self {
        Self {
            document_code: "V".to_string(),
            issuing_country: String::new(),
            document_number: String::new(),
            surname: String::new(),
            given_names: String::new(),
            nationality: String::new(),
            date_of_birth: String::new(),
            sex: String::new(),
            date_of_expiry: String::new(),
            optional_data: None,
        }
    }
}

/// Emit an MRV-B (machine readable visa) MRZ: two 36-character lines joined
/// by `\n`.
///
/// The document number, date-of-birth, and date-of-expiry check digits are
/// computed from `fields` — the result always round-trips through
/// [`crate::parse_mrv_b`] with `valid() == true` (see `tests/roundtrip.rs`).
/// MRV-B has no personal-number check digit and no composite check digit.
pub fn format_mrv_b(fields: &MrvBFields) -> String {
    let doc_code = field(&fields.document_code, 2);
    let issuing = field(&fields.issuing_country, 3);
    let name = name_field(&fields.surname, &fields.given_names, 31);
    let line1 = format!("{doc_code}{issuing}{name}");
    debug_assert_eq!(line1.len(), 36);

    let doc_num = field(&fields.document_number, 9);
    let doc_num_check = digit_char(&doc_num);
    let nationality = field(&fields.nationality, 3);
    let dob = field(&fields.date_of_birth, 6);
    let dob_check = digit_char(&dob);
    let sex = match fields.sex.to_ascii_uppercase().as_str() {
        "M" => 'M',
        "F" => 'F',
        _ => '<',
    };
    let expiry = field(&fields.date_of_expiry, 6);
    let expiry_check = digit_char(&expiry);
    let optional = field(fields.optional_data.as_deref().unwrap_or(""), 8);

    let line2 = format!(
        "{doc_num}{doc_num_check}{nationality}{dob}{dob_check}{sex}{expiry}{expiry_check}{optional}"
    );
    debug_assert_eq!(line2.len(), 36);

    format!("{line1}\n{line2}")
}