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
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
//! ICAO 9303 / ISO 3166-1 alpha-3 issuing-state & nationality code ↔ name.
//!
//! The MRZ carries a code in a three-cell field for the issuing state and the holder's
//! nationality. [`country_name`] maps that code to a human-readable name so
//! callers can enrich the extraction (`issuing_country_name`,
//! `nationality_name`); [`code_for_name`] is the reverse direction, needed
//! when a Tier-2 LLM read prints the full name ("CROATIA") instead of the
//! MRZ code (`HRV`) and a downstream normalizer wants the canonical code.
//!
//! Both functions read the same `CODES` table — single-sourced, so the two
//! directions can never drift apart — which holds every ISO 3166-1 alpha-3
//! code in the UN M49 list as of 2026-09-25, plus the ICAO 9303 codes: stateless/refugee/
//! organization codes, `GBR` nationality subvariants, and specimen code `UTO`.
//! ISO 3166-1 changes over time, so an unlisted code can still be legitimate. Zero dependencies, just `&'static str`
//! literals, so it compiles for native and wasm alike.
//!
//! [`code_for_name`] also falls back to `ALTERNATE_NAMES` — former official
//! names, alternate UN long/short forms, and diacritic-dropped spellings —
//! once `CODES` itself declines. See that table's doc comment for what
//! belongs there and what belongs in `synthpass-core::normalize::DEMONYMS`
//! instead.

/// `(code, name)` pairs, in the same order as the original per-region match
/// arms. Order matters for [`code_for_name`]: a couple of names have more
/// than one legitimate code on real documents (Kosovo: user-assigned `XKX`/ICAO `RKS`; Germany:
/// `DEU`/`D`, ICAO's current single-letter code) — [`code_for_name`] returns the
/// first match. For Kosovo this is the user-assigned `XKX`, because it
/// appears before ICAO's `RKS`; for Germany it is ISO `DEU`, before ICAO `D`.
const CODES: &[(&str, &str)] = &[
    // ── Africa ──
    ("DZA", "Algeria"),
    ("AGO", "Angola"),
    ("BEN", "Benin"),
    ("BWA", "Botswana"),
    ("BFA", "Burkina Faso"),
    ("BDI", "Burundi"),
    ("CPV", "Cabo Verde"),
    ("CMR", "Cameroon"),
    ("CAF", "Central African Republic"),
    ("TCD", "Chad"),
    ("COM", "Comoros"),
    ("COG", "Congo"),
    ("COD", "Congo (Democratic Republic of the)"),
    ("CIV", "Côte d'Ivoire"),
    ("DJI", "Djibouti"),
    ("EGY", "Egypt"),
    ("GNQ", "Equatorial Guinea"),
    ("ERI", "Eritrea"),
    ("SWZ", "Eswatini"),
    ("ETH", "Ethiopia"),
    ("GAB", "Gabon"),
    ("GMB", "Gambia"),
    ("GHA", "Ghana"),
    ("GIN", "Guinea"),
    ("GNB", "Guinea-Bissau"),
    ("KEN", "Kenya"),
    ("LSO", "Lesotho"),
    ("LBR", "Liberia"),
    ("LBY", "Libya"),
    ("MDG", "Madagascar"),
    ("MWI", "Malawi"),
    ("MLI", "Mali"),
    ("MRT", "Mauritania"),
    ("MUS", "Mauritius"),
    ("MAR", "Morocco"),
    ("MOZ", "Mozambique"),
    ("NAM", "Namibia"),
    ("NER", "Niger"),
    ("NGA", "Nigeria"),
    ("RWA", "Rwanda"),
    ("STP", "Sao Tome and Principe"),
    ("SEN", "Senegal"),
    ("SYC", "Seychelles"),
    ("SLE", "Sierra Leone"),
    ("SOM", "Somalia"),
    ("ZAF", "South Africa"),
    ("SSD", "South Sudan"),
    ("SDN", "Sudan"),
    ("TZA", "Tanzania"),
    ("TGO", "Togo"),
    ("TUN", "Tunisia"),
    ("UGA", "Uganda"),
    ("ZMB", "Zambia"),
    ("ZWE", "Zimbabwe"),
    ("ESH", "Western Sahara"),
    // ── Americas ──
    ("ATG", "Antigua and Barbuda"),
    ("ARG", "Argentina"),
    ("BHS", "Bahamas"),
    ("BRB", "Barbados"),
    ("BLZ", "Belize"),
    ("BOL", "Bolivia"),
    ("BRA", "Brazil"),
    ("CAN", "Canada"),
    ("CHL", "Chile"),
    ("COL", "Colombia"),
    ("CRI", "Costa Rica"),
    ("CUB", "Cuba"),
    ("DMA", "Dominica"),
    ("DOM", "Dominican Republic"),
    ("ECU", "Ecuador"),
    ("SLV", "El Salvador"),
    ("GRD", "Grenada"),
    ("GTM", "Guatemala"),
    ("GUY", "Guyana"),
    ("HTI", "Haiti"),
    ("HND", "Honduras"),
    ("JAM", "Jamaica"),
    ("MEX", "Mexico"),
    ("NIC", "Nicaragua"),
    ("PAN", "Panama"),
    ("PRY", "Paraguay"),
    ("PER", "Peru"),
    ("KNA", "Saint Kitts and Nevis"),
    ("LCA", "Saint Lucia"),
    ("VCT", "Saint Vincent and the Grenadines"),
    ("SUR", "Suriname"),
    ("TTO", "Trinidad and Tobago"),
    ("USA", "United States of America"),
    ("URY", "Uruguay"),
    ("VEN", "Venezuela"),
    // ── Asia ──
    ("AFG", "Afghanistan"),
    ("ARM", "Armenia"),
    ("AZE", "Azerbaijan"),
    ("BHR", "Bahrain"),
    ("BGD", "Bangladesh"),
    ("BTN", "Bhutan"),
    ("BRN", "Brunei Darussalam"),
    ("KHM", "Cambodia"),
    ("CHN", "China"),
    ("CYP", "Cyprus"),
    ("GEO", "Georgia"),
    ("HKG", "Hong Kong"),
    ("IND", "India"),
    ("IDN", "Indonesia"),
    ("IRN", "Iran"),
    ("IRQ", "Iraq"),
    ("ISR", "Israel"),
    ("JPN", "Japan"),
    ("JOR", "Jordan"),
    ("KAZ", "Kazakhstan"),
    ("PRK", "Korea (Democratic People's Republic of)"),
    ("KOR", "Korea (Republic of)"),
    ("KWT", "Kuwait"),
    ("KGZ", "Kyrgyzstan"),
    ("LAO", "Lao People's Democratic Republic"),
    ("LBN", "Lebanon"),
    ("MAC", "Macao"),
    ("MYS", "Malaysia"),
    ("MDV", "Maldives"),
    ("MNG", "Mongolia"),
    ("MMR", "Myanmar"),
    ("NPL", "Nepal"),
    ("OMN", "Oman"),
    ("PAK", "Pakistan"),
    ("PSE", "Palestine"),
    ("PHL", "Philippines"),
    ("QAT", "Qatar"),
    ("SAU", "Saudi Arabia"),
    ("SGP", "Singapore"),
    ("LKA", "Sri Lanka"),
    ("SYR", "Syrian Arab Republic"),
    ("TWN", "Taiwan"),
    ("TJK", "Tajikistan"),
    ("THA", "Thailand"),
    ("TLS", "Timor-Leste"),
    ("TUR", "Türkiye"),
    ("TKM", "Turkmenistan"),
    ("ARE", "United Arab Emirates"),
    ("UZB", "Uzbekistan"),
    ("VNM", "Viet Nam"),
    ("YEM", "Yemen"),
    // ── Europe ──
    ("ALB", "Albania"),
    ("AND", "Andorra"),
    ("AUT", "Austria"),
    ("BLR", "Belarus"),
    ("BEL", "Belgium"),
    ("BIH", "Bosnia and Herzegovina"),
    ("BGR", "Bulgaria"),
    ("HRV", "Croatia"),
    ("CZE", "Czechia"),
    ("DNK", "Denmark"),
    ("EST", "Estonia"),
    ("FIN", "Finland"),
    ("FRA", "France"),
    ("DEU", "Germany"),
    ("GRC", "Greece"),
    ("HUN", "Hungary"),
    ("ISL", "Iceland"),
    ("IRL", "Ireland"),
    ("ITA", "Italy"),
    ("XKX", "Kosovo"),
    ("LVA", "Latvia"),
    ("LIE", "Liechtenstein"),
    ("LTU", "Lithuania"),
    ("LUX", "Luxembourg"),
    ("MLT", "Malta"),
    ("MDA", "Moldova"),
    ("MCO", "Monaco"),
    ("MNE", "Montenegro"),
    ("NLD", "Netherlands"),
    ("MKD", "North Macedonia"),
    ("NOR", "Norway"),
    ("POL", "Poland"),
    ("PRT", "Portugal"),
    ("ROU", "Romania"),
    ("RUS", "Russian Federation"),
    ("SMR", "San Marino"),
    ("SRB", "Serbia"),
    ("SVK", "Slovakia"),
    ("SVN", "Slovenia"),
    ("ESP", "Spain"),
    ("SWE", "Sweden"),
    ("CHE", "Switzerland"),
    ("UKR", "Ukraine"),
    ("GBR", "United Kingdom"),
    ("VAT", "Holy See (Vatican City State)"),
    // ── Oceania ──
    ("AUS", "Australia"),
    ("FJI", "Fiji"),
    ("KIR", "Kiribati"),
    ("MHL", "Marshall Islands"),
    ("FSM", "Micronesia (Federated States of)"),
    ("NRU", "Nauru"),
    ("NZL", "New Zealand"),
    ("PLW", "Palau"),
    ("PNG", "Papua New Guinea"),
    ("WSM", "Samoa"),
    ("SLB", "Solomon Islands"),
    ("TON", "Tonga"),
    ("TUV", "Tuvalu"),
    ("VUT", "Vanuatu"),
    // ── Territories & dependencies commonly seen on documents ──
    ("ABW", "Aruba"),
    ("BMU", "Bermuda"),
    ("CYM", "Cayman Islands"),
    ("CUW", "Curaçao"),
    ("FRO", "Faroe Islands"),
    ("GIB", "Gibraltar"),
    ("GRL", "Greenland"),
    ("SXM", "Sint Maarten (Dutch part)"),
    // ── ICAO 9303 special / non-ISO codes ──
    ("UTO", "Utopia (ICAO specimen)"),
    ("D", "Germany"), // current ICAO single-letter code (Part 3 §5 Part A)
    ("EUE", "European Union"),
    ("RKS", "Kosovo"), // ICAO Part 3 §5 code
    // British nationality subvariants used in the MRZ nationality field
    ("GBD", "British Overseas Territories Citizen"),
    ("GBN", "British National (Overseas)"),
    ("GBO", "British Overseas Citizen"),
    ("GBP", "British Protected Person"),
    ("GBS", "British Subject"),
    // Stateless persons, refugees and unspecified nationality
    ("XXA", "Stateless person (1954 Convention)"),
    ("XXB", "Refugee (1951 Convention)"),
    ("XXC", "Refugee (other)"),
    ("XXX", "Unspecified nationality"),
    // Inter-governmental organizations issuing travel documents
    ("UNO", "United Nations Organization"),
    ("UNA", "United Nations specialized agency"),
    (
        "UNK",
        "Resident of Kosovo to whom a travel document has been issued by the United Nations Interim Administration Mission in Kosovo (UNMIK)",
    ),
    ("XOM", "Sovereign Military Order of Malta"),
    ("XBA", "African Development Bank"),
    ("XIM", "African Export-Import Bank"),
    ("XCC", "Caribbean Community (CARICOM)"),
    (
        "XCO",
        "Common Market for Eastern and Southern Africa (COMESA)",
    ),
    ("XEC", "Economic Community of West African States (ECOWAS)"),
    (
        "XPO",
        "International Criminal Police Organization (INTERPOL)",
    ),
    ("XCE", "Council of Europe"),
    ("XES", "Organization of Eastern Caribbean States (OECS)"),
    ("XMP", "Parliamentary Assembly of the Mediterranean (PAM)"),
    ("XDC", "Southern African Development Community"),
    // Deprecated but valid — may still appear on documents issued before the
    // code was withdrawn.
    ("ANT", "Netherlands Antilles"),
    ("NTZ", "Neutral Zone"),
    // ICAO-internal: used only when ICAO itself digitally signs a master list.
    ("IAO", "International Civil Aviation Organization"),
    // ── ISO 3166-1 dependent territories and other areas ──
    // The 42 ISO 3166-1 alpha-3 codes this table lacked (#425), with names exactly as
    // the UN Statistics Division's M49 list prints them (retrieved 2026-09-25,
    // https://unstats.un.org/unsd/methodology/m49/overview/). None is a sovereign
    // state.
    ("AIA", "Anguilla"),
    ("ALA", "Åland Islands"),
    ("ASM", "American Samoa"),
    ("ATA", "Antarctica"),
    ("ATF", "French Southern Territories"),
    ("BES", "Bonaire, Sint Eustatius and Saba"),
    ("BLM", "Saint Barthélemy"),
    ("BVT", "Bouvet Island"),
    ("CCK", "Cocos (Keeling) Islands"),
    ("COK", "Cook Islands"),
    ("CXR", "Christmas Island"),
    ("FLK", "Falkland Islands (Malvinas)"),
    ("GGY", "Guernsey"),
    ("GLP", "Guadeloupe"),
    ("GUF", "French Guiana"),
    ("GUM", "Guam"),
    ("HMD", "Heard Island and McDonald Islands"),
    ("IMN", "Isle of Man"),
    ("IOT", "British Indian Ocean Territory"),
    ("JEY", "Jersey"),
    ("MAF", "Saint Martin (French Part)"),
    ("MNP", "Northern Mariana Islands"),
    ("MSR", "Montserrat"),
    ("MTQ", "Martinique"),
    ("MYT", "Mayotte"),
    ("NCL", "New Caledonia"),
    ("NFK", "Norfolk Island"),
    ("NIU", "Niue"),
    ("PCN", "Pitcairn"),
    ("PRI", "Puerto Rico"),
    ("PYF", "French Polynesia"),
    ("REU", "Réunion"),
    ("SGS", "South Georgia and the South Sandwich Islands"),
    ("SHN", "Saint Helena"),
    ("SJM", "Svalbard and Jan Mayen Islands"),
    ("SPM", "Saint Pierre and Miquelon"),
    ("TCA", "Turks and Caicos Islands"),
    ("TKL", "Tokelau"),
    ("UMI", "United States Minor Outlying Islands"),
    ("VGB", "British Virgin Islands"),
    ("VIR", "United States Virgin Islands"),
    ("WLF", "Wallis and Futuna Islands"),
];

/// Alternate country **names** [`code_for_name`] resolves after `CODES`
/// itself has declined — a former official English name (`Czechia` was
/// `Czech Republic` until 2016; `Türkiye` was `Turkey` until its 2022 UN
/// notification), an ICAO/UN long-form name distinct from `CODES`'s short
/// one (`Korea (Republic of)` vs `Republic of Korea`; `United Kingdom` vs its
/// full `United Kingdom of Great Britain and Northern Ireland`), or the same
/// name with `CODES`'s diacritic dropped (`Türkiye` -> `Turkiye`,
/// `Azərbaycan` -> `Azerbaycan`) — exactly the shapes a document's visual
/// zone prints and OCR/Tier-2 reproduces, instead of the MRZ code.
///
/// **Not demonyms.** `CANADIAN`, `SERBIAN`, `ESPAÑOLA` — adjectives
/// describing a *person's* nationality, not a country's name — have no place
/// in this table and live in `synthpass-core::normalize::DEMONYMS` instead.
/// That table is this one's deliberate mirror: same
/// one-entry-per-observed-form discipline, same accept rule
/// (`vocab_replay`, `>=1` miss flipped to hit and `0` flipped the other
/// way), different vocabulary — a country can be named in a hundred
/// languages, but only [`code_for_name`]'s caller (a country/nationality
/// field, never a free-text one) ever needs any of them resolved.
///
/// Checked only after `CODES` itself has declined, so it can never reorder
/// or override that table's own alias resolution (Germany's `D`/`DEU`,
/// Kosovo's `XKX`/`RKS`).
///
/// **Every entry here was observed in the prompt-v3 parity corpus, and the
/// table as a whole is proved by a measurement**: flips real Tier-2 answers
/// from miss to hit against `crates/synthpass-llm/tests/parity.rs`'s logged
/// run (issue #539, CI run 36323412121), with zero regressions. See
/// `knowledge/benchmarks/normalize-country-demonyms-2026-09-27.md`.
#[rustfmt::skip]
const ALTERNATE_NAMES: &[(&str, &str)] = &[
    ("Turkiye", "TUR"), ("Turkey", "TUR"), ("Republic of Turkey", "TUR"),
    ("Republic of Korea", "KOR"),
    ("Czech Republic", "CZE"),
    ("United Kingdom of Great Britain and Northern Ireland", "GBR"),
    ("Islamic Republic of Afghanistan", "AFG"),
    ("Azerbaycan", "AZE"),
    ("Polska", "POL"),
];

/// Map an ICAO/ISO 3166-1 code (usually three letters; ICAO `D` is one) to a country or entity name.
/// Returns `None` for codes not in the table.
///
/// The table holds every ISO 3166-1 alpha-3 code in the UN M49 list (2026-09-25)
/// and the Doc 9303 Part 3 §5 additions, including organization,
/// stateless/refugee and specimen codes. ISO 3166-1 changes over time, so
/// `None` does not prove a code invalid.
/// `find_and_parse` uses recognition as a guard in its repair passes; direct
/// `parse_*` calls do not validate country codes.
///
/// ```
/// assert_eq!(mrz::country_name("DEU"), Some("Germany"));
/// assert_eq!(mrz::country_name("UTO"), Some("Utopia (ICAO specimen)"));
/// assert_eq!(mrz::country_name("XXA"), Some("Stateless person (1954 Convention)"));
/// assert_eq!(mrz::country_name("ZZZ"), None);
/// ```
pub fn country_name(code: &str) -> Option<&'static str> {
    CODES
        .iter()
        .find(|&&(c, _)| c == code)
        .map(|&(_, name)| name)
}

/// Map a country or entity name back to its ICAO/ISO 3166-1 code —
/// the reverse of [`country_name`], over the same `CODES` table so the two
/// directions can't drift apart. Case-insensitive (Tier-2 LLM reads commonly
/// come back upper/lower/title-cased inconsistently, e.g. `"CROATIA"` vs
/// `"Croatia"`). Returns `None` for names not in the table; when a name has
/// more than one legitimate code (Kosovo, Germany — see `CODES`'s doc
/// comment), the first code in table order wins (`XKX` for Kosovo, `DEU` for Germany).
///
/// Falls back to `ALTERNATE_NAMES` when `CODES` itself declines — a
/// former official name, a long/short UN form, or the same name with a
/// diacritic dropped (see that table's doc comment) — so it can never
/// override `CODES`'s own alias resolution for Germany or Kosovo.
///
/// ```
/// assert_eq!(mrz::code_for_name("Germany"), Some("DEU"));
/// assert_eq!(mrz::code_for_name("CROATIA"), mrz::code_for_name("Croatia"));
/// assert_eq!(mrz::code_for_name("Turkey"), Some("TUR")); // pre-2022 English name
/// ```
pub fn code_for_name(name: &str) -> Option<&'static str> {
    CODES
        .iter()
        .find(|&&(_, n)| n.eq_ignore_ascii_case(name))
        .map(|&(c, _)| c)
        .or_else(|| {
            ALTERNATE_NAMES
                .iter()
                .find(|&&(n, _)| n.eq_ignore_ascii_case(name))
                .map(|&(_, c)| c)
        })
}

/// Every `(code, name)` pair [`country_name`] and [`code_for_name`] are built
/// on, in table order.
///
/// Exists for a caller that needs to detect when this table itself changes —
/// e.g. a vocabulary fingerprint one layer up that hashes every table a
/// normalizer dispatches on, so a run can prove which country data it was
/// compiled against. Not needed for ordinary lookups: use [`country_name`] or
/// [`code_for_name`] for those.
///
/// ```
/// assert!(mrz::codes().contains(&("DEU", "Germany")));
/// ```
pub fn codes() -> &'static [(&'static str, &'static str)] {
    CODES
}

/// Every `(name, code)` pair `ALTERNATE_NAMES` holds, in table order —
/// [`codes`]'s sibling accessor for the fallback table [`code_for_name`]
/// consults after `CODES` itself declines.
///
/// Exists for the same reason [`codes`] does: a caller one layer up —
/// `synthpass_core::normalize::vocabulary_fingerprint` — hashes every table a
/// country/nationality lookup can resolve through, and this table is exactly
/// as capable of moving that resolution as `CODES` itself.
///
/// ```
/// assert!(mrz::alternate_names().contains(&("Turkey", "TUR")));
/// ```
pub fn alternate_names() -> &'static [(&'static str, &'static str)] {
    ALTERNATE_NAMES
}

/// Whether two ICAO/ISO 3166-1 codes name the same country or entity.
///
/// Not the same question as `a == b`, because `CODES` deliberately carries
/// more than one legitimate code for some entities (Germany: `DEU` and ICAO's
/// current single-letter `D`; Kosovo: user-assigned `XKX` and ICAO `RKS` — see `CODES`'s doc
/// comment). A German passport prints `D` in the MRZ, while any name-based
/// resolution of "Germany" goes through [`code_for_name`], which returns the
/// primary code `DEU`. Comparing those two as plain strings reports a
/// disagreement between two readings that agree perfectly.
///
/// Unrecognized codes compare by case-insensitive equality only: with no
/// table entry there is nothing to resolve them through, and two unknown
/// strings being equal is the most that can honestly be said about them.
///
/// ```
/// assert!(mrz::codes_equivalent("D", "DEU")); // current ICAO German code
/// assert!(!mrz::codes_equivalent("DEU", "AUT"));
/// ```
pub fn codes_equivalent(a: &str, b: &str) -> bool {
    if a.eq_ignore_ascii_case(b) {
        return true;
    }
    // Case-insensitive on both sides so this can't quietly answer `false`
    // for a caller that hasn't uppercased its input — the fast path above is
    // already case-insensitive, and a lookup that isn't would make the two
    // halves of this function disagree about what "the same code" means.
    fn name_of(code: &str) -> Option<&'static str> {
        CODES
            .iter()
            .find(|&&(c, _)| c.eq_ignore_ascii_case(code))
            .map(|&(_, name)| name)
    }
    match (name_of(a), name_of(b)) {
        (Some(x), Some(y)) => x == y,
        _ => false,
    }
}

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

    #[test]
    fn maps_representative_codes_neutrally() {
        // Ordinary members.
        assert_eq!(country_name("HRV"), Some("Croatia"));
        assert_eq!(country_name("SRB"), Some("Serbia"));
        assert_eq!(country_name("SVN"), Some("Slovenia"));
        // Politically sensitive entries are present, per the standard — the
        // parser must name whatever a real document prints.
        assert_eq!(country_name("TWN"), Some("Taiwan"));
        assert_eq!(country_name("PSE"), Some("Palestine"));
        assert_eq!(country_name("XKX"), Some("Kosovo"));
        // ICAO specials.
        assert_eq!(country_name("UTO"), Some("Utopia (ICAO specimen)"));
        assert_eq!(country_name("GBN"), Some("British National (Overseas)"));
        assert_eq!(country_name("XXB"), Some("Refugee (1951 Convention)"));
        // Unknown / empty.
        assert_eq!(country_name("ZZZ"), None);
        assert_eq!(country_name(""), None);
    }

    #[test]
    fn maps_seven_additional_codes() {
        // Part 3 §5 registry, Parts A-H — segment S5 added these after a broad
        // diff against the codes already present in `CODES`.
        assert_eq!(country_name("XCE"), Some("Council of Europe"));
        assert_eq!(
            country_name("XES"),
            Some("Organization of Eastern Caribbean States (OECS)")
        );
        assert_eq!(
            country_name("XMP"),
            Some("Parliamentary Assembly of the Mediterranean (PAM)")
        );
        assert_eq!(
            country_name("XDC"),
            Some("Southern African Development Community")
        );
        assert_eq!(country_name("ANT"), Some("Netherlands Antilles"));
        assert_eq!(country_name("NTZ"), Some("Neutral Zone"));
        assert_eq!(
            country_name("IAO"),
            Some("International Civil Aviation Organization")
        );
    }

    #[test]
    fn reverse_lookup_is_case_insensitive_and_round_trips() {
        assert_eq!(code_for_name("Croatia"), Some("HRV"));
        assert_eq!(code_for_name("CROATIA"), Some("HRV"));
        assert_eq!(code_for_name("croatia"), Some("HRV"));
        assert_eq!(code_for_name("Taiwan"), Some("TWN"));
        assert_eq!(code_for_name("Not A Country"), None);
        assert_eq!(code_for_name(""), None);
    }

    #[test]
    fn reverse_lookup_prefers_the_primary_code_for_aliased_names() {
        // Kosovo and Germany each have two legitimate codes in the table;
        // the primary ISO/ICAO code (appearing first) must win.
        assert_eq!(code_for_name("Kosovo"), Some("XKX"));
        assert_eq!(code_for_name("Germany"), Some("DEU"));
    }

    #[test]
    fn part3_authority_codes_have_verified_names() {
        assert_eq!(country_name("UNK"), Some("Resident of Kosovo to whom a travel document has been issued by the United Nations Interim Administration Mission in Kosovo (UNMIK)"));
        assert_eq!(
            country_name("XCO"),
            Some("Common Market for Eastern and Southern Africa (COMESA)")
        );
        assert_eq!(
            country_name("XPO"),
            Some("International Criminal Police Organization (INTERPOL)")
        );
    }

    #[test]
    fn aliased_codes_are_equivalent_to_their_primary_code() {
        // The case this function exists for: German documents print the
        // ICAO `D` in the MRZ, while any name-based resolution of
        // "Germany" yields `DEU`. They are the same country.
        assert!(codes_equivalent("D", "DEU"));
        assert!(codes_equivalent("DEU", "D"));
        assert!(codes_equivalent("XKX", "RKS"));
    }

    #[test]
    fn distinct_countries_are_never_equivalent() {
        assert!(!codes_equivalent("DEU", "AUT"));
        assert!(!codes_equivalent("D", "DNK"));
        // Unrecognized codes have nothing to resolve through, so only exact
        // (case-insensitive) equality can be claimed for them.
        assert!(!codes_equivalent("ZZZ", "DEU"));
        assert!(!codes_equivalent("ZZZ", "QQQ"));
        assert!(codes_equivalent("ZZZ", "zzz"));
        // Empty is not a wildcard.
        assert!(!codes_equivalent("", "DEU"));
    }

    #[test]
    fn equivalence_is_case_insensitive_through_the_table_too() {
        assert!(codes_equivalent("d", "deu"));
        assert!(codes_equivalent("Deu", "D"));
    }

    #[test]
    fn every_code_is_equivalent_to_itself_and_to_its_aliases() {
        // Reflexivity over the whole table, plus the symmetry/transitivity
        // that the shared-name definition implies: any two codes naming the
        // same entity must compare equal in both directions.
        for &(code, name) in CODES {
            assert!(codes_equivalent(code, code), "{code} vs itself");
            for &(other, other_name) in CODES {
                if name == other_name {
                    assert!(
                        codes_equivalent(code, other) && codes_equivalent(other, code),
                        "{code} and {other} both name {name}"
                    );
                }
            }
        }
    }

    #[test]
    fn every_table_entry_round_trips_through_both_directions() {
        for &(code, name) in CODES {
            assert_eq!(
                country_name(code),
                Some(name),
                "country_name({code:?}) should return {name:?}"
            );
            // Not asserting code_for_name(name) == code here: several names
            // have more than one valid code (see the alias test above), so
            // this only checks the reverse lookup resolves to *some* valid
            // code that maps back to the same name.
            let reverse = code_for_name(name).expect("name should resolve back to a code");
            assert_eq!(country_name(reverse), Some(name));
        }
    }

    // ── ALTERNATE_NAMES ──

    /// Every case here is a real Tier-2 `actual=` value from the prompt-v3
    /// parity run reviewed in issue #539 (CI run 36323412121) that
    /// `code_for_name` passed through unresolved. See
    /// `knowledge/benchmarks/normalize-country-demonyms-2026-09-27.md`.
    #[test]
    fn code_for_name_resolves_an_alternate_name_after_codes_declines() {
        assert_eq!(code_for_name("Turkiye"), Some("TUR"));
        assert_eq!(code_for_name("TURKEY"), Some("TUR"));
        assert_eq!(code_for_name("Republic of Turkey"), Some("TUR"));
        assert_eq!(code_for_name("REPUBLIC OF KOREA"), Some("KOR"));
        assert_eq!(code_for_name("Czech Republic"), Some("CZE"));
        assert_eq!(
            code_for_name("United Kingdom of Great Britain and Northern Ireland"),
            Some("GBR")
        );
        assert_eq!(
            code_for_name("Islamic Republic of Afghanistan"),
            Some("AFG")
        );
        assert_eq!(code_for_name("Azerbaycan"), Some("AZE"));
        assert_eq!(code_for_name("Polska"), Some("POL"));
    }

    #[test]
    fn alternate_names_do_not_shadow_the_primary_table() {
        // Each entry must resolve something `CODES` itself cannot, or it is
        // dead weight nobody would notice going stale.
        for &(name, code) in ALTERNATE_NAMES {
            assert!(
                !CODES.iter().any(|&(_, n)| n.eq_ignore_ascii_case(name)),
                "{name:?} is already resolved by CODES — drop it from ALTERNATE_NAMES"
            );
            assert!(
                country_name(code).is_some(),
                "{name:?} maps to {code:?}, which is not a code CODES knows"
            );
        }
    }

    #[test]
    fn alternate_names_accessor_matches_the_table() {
        assert_eq!(alternate_names(), ALTERNATE_NAMES);
        assert!(alternate_names().contains(&("Turkey", "TUR")));
    }
}