Expand description
ICAO 9303 Machine Readable Zone parser, emitter, and check-digit validator.
Zero runtime dependencies, no unsafe, and no clock or network access, so it
compiles to native and wasm32-unknown-unknown targets alike and gives the
same answer on both. Supports:
- TD3 (passports): 2 lines × 44 characters
- TD2 (official travel documents / ID cards): 2 lines × 36 characters
- TD1 (ID cards): 3 lines × 30 characters
- MRV-A (visas, passport-book size): 2 lines × 44 characters
- MRV-B (visas, smaller size): 2 lines × 36 characters
Check digits use the standard 7-3-1 weighting over the value mapping
0-9 → 0-9, A-Z → 10-35, < → 0. A field checksum that validates is
deterministic evidence — arithmetic, not a probabilistic model. What it
establishes is that the candidate is checksum-consistent with the printed
check digit. It is a strong filter and a weak oracle: it does not establish
byte-identity with the printed zone, and it constrains only the fields a
digit actually covers — on TD2 and TD3 the whole of line 1, names included,
carries no check digit at all. Blindspot is the exact account.
let doc = mrz::parse_td3(
"P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<",
"L898902C36UTO7408122F1204159ZE184226B<<<<<10",
).unwrap();
assert_eq!(doc.surname, "ERIKSSON");
assert_eq!(doc.date_of_birth.to_string(), "1974-08-12"); // expanded to ISO 8601
// Per-field evidence, not a single boolean.
assert_eq!(doc.checks.document_number, Some(true));
assert_eq!(doc.checks.composite, Some(true));
assert!(doc.valid()); // every printed check digit verifiedparse_td1, parse_td2, parse_mrv_a and parse_mrv_b cover the other
formats.
§Where to start
| You have | Reach for |
|---|---|
| MRZ lines, already separated | parse_td3, parse_td2, parse_td1, parse_mrv_a, parse_mrv_b |
| Free-form OCR text | find_and_parse — finds the zone, repairs it only under check-digit agreement |
| Fields to print as an MRZ | format_td3 and its siblings, fed by Td3Fields and friends |
| A name in a national script | transliterate (Doc 9303 Part 3 §6 A, Latin), transliterate_cyrillic (§6 B, Cyrillic), encode_name_component |
| A number too long for its field | MrzData::full_document_number |
| A parsed record to judge | MrzData::valid for the read, MrzData::validity for the document’s dates |
| A glyph the OCR could not read | solve_field, solve_substitution, and Blindspot for what no check digit can catch |
| Cells an image shows as covered | apply_occlusion with a CellMask: it withholds fields no check digit covers, and refuses a covered check-digit cell |
A valid composite check digit establishes checksum consistency, not
byte-identity. It does not prove the document is in date — see
MrzData::validity — and its blind set is exactly characterised, both
for single substitutions and for the combinations of individually-caught
ones that cancel mod 10 — see Blindspot.
§Feature flags
Both are off by default, which keeps the default build zero-dependency:
serde— derivesSerializeandDeserializeon the data types:MrzData,Checks,Format,Field,SequenceCompleteness,ParseOptions,Date,DateValidity,DateCompleteness,ZoneField,Occluded, and the five emitter inputs (Td3Fields,Td2Fields,Td1Fields,MrvAFields,MrvBFields).MrzDateandSeximplement both by hand as their text form (ADR-0020), soMrzData’s dates and sex serialise as strings.zeroize— derivesZeroizeOnDroponMrzData, wiping its PII-bearing fields from memory when the value is dropped. Best-effort: seeMrzDatafor what it does not reach. AnOccluded::dataand aLine1Verdict::Proposedread areMrzDatavalues and wipe the same way.
§Stability
The crate is pre-1.0, so the minor version is the breaking slot: ^0.9
resolves any 0.9.x but never 0.10.0. Output types (MrzData,
Checks, Format, Field, MrzError, SequenceCompleteness and
the other enums) are #[non_exhaustive], so they can grow in a patch
release; the five *Fields emitter inputs are deliberately exhaustive, so
that struct-update syntax (..Default::default()) keeps working. The minimum
supported Rust version is 1.82, and raising it is a minor-version change.
Release history is in the changelog, and what each version slot is for, up to 1.0, is in the roadmap.
§Source layout
The engine is split across private modules, whose public items are all re-exported at the crate root:
parser— the five fixed-layout parsers and the free-text scannerocclusion—apply_occlusion,CellMask,Occluded,ZoneField(withholds covered, unverifiable fields from a parsed zone)line1_select— the shadow line-1 selector,select_line1(opt-in; measured once, see its docs)emit— the five emitters and Part 3 §4.6 name encodingchecksum— check-digit math and OCR line normalizationrepair— check-digit-guided recovery of damaged or misread fieldsblindspot— the substitutions check digits provably cannot catchdates—YYMMDDexpansion, the calendar, and date plausibilitycountries— a subset of Part 3 §5 state and organization codesdoccode— Part 4 §4.4 secondary passport document codestranslit— Part 3 §6 A (Latin) and §6 B (Cyrillic) transliteration
Structs§
- Cell
Mask - A bitmask of covered cells within one MRZ zone, for
apply_occlusion. - Checks
- Per-field check-digit verification results.
- Date
- A simple proleptic-Gregorian calendar date. Used as the “today” reference
for
crate::MrzData::validityand to measure days-until-expiry. - Date
Validity - Date-plausibility summary for an MRZ, relative to a reference “today”.
Distinct from the check digits: a checksum-valid MRZ can still be expired
or carry impossible dates. Obtain one from
MrzData::validity. - Invalid
RawDate Field - Rejection from
RawDateField::try_from: the text was not exactly six characters of the MRZ alphabet (0-9,A-Z,<). - Line1
Selection - What
select_line1found. Off by default in every caller in this workspace. - MrvA
Fields - Raw MRV-A sub-fields, in MRZ-native form — the same input conventions as
Td3Fields. - MrvB
Fields - Raw MRV-B sub-fields, in MRZ-native form — the same input conventions as
Td3Fields. - MrzData
- Parsed and validated MRZ data.
- Occluded
- The result of
apply_occlusion: a parsed zone with every masked, unverifiable field withheld. - Parse
MrzDate Error - Rejection from parsing an
MrzDate’s text form. - Parse
Options - Tunables for the parsing entry points.
- Parse
SexError - Rejection from parsing a
Sex’s text form: it is exactly one MRZ-alphabet character. - RawDate
Field - The six characters of an MRZ date field, exactly as printed.
- Td1Fields
- Raw TD1 sub-fields, in MRZ-native form — the same input conventions as
Td3Fields. - Td2Fields
- Raw TD2 sub-fields, in MRZ-native form — the same input conventions as
Td3Fields. - Td3Fields
- Raw TD3 sub-fields, in MRZ-native form.
Enums§
- Blindspot
- Whether a check digit can distinguish two MRZ characters.
- Cyrillic
Language - Which language’s ICAO 9303 Part 3 §6 B column to apply.
- Date
Completeness - How much of a six-character MRZ date field is actually known.
- Date
Role - Which date a field holds, which decides the century of a two-digit year.
- Field
- Which check-digit-bearing field an error refers to.
- Field
Kind - Which ICAO field a
solve_fieldcall is resolving. Selects the structural constraint applied after the check digit, never instead of it. - Format
- Which ICAO 9303 layout a zone uses.
- Line1
Unresolved - Why
select_line1left a zoneUnresolved: which offind_and_parse_with’s wrong-physical-line checks flagged it. - Line1
Verdict - The verdict of
select_line1. - MrzDate
- What an MRZ date field holds.
- MrzError
- Why parsing an MRZ zone failed outright — distinct from a failed check
digit, which
parse_*reports throughChecksinstead of an error. - Passport
Type - The passport type a §4.4 secondary document code designates.
- Resolution
- What the check digit could prove about a field carrying
UNKNOWNs. - Sequence
Completeness - A single completeness signal spanning both outcomes of a
find_and_parseattempt. - Sex
- What the MRZ sex cell holds.
- Transliteration
Style - Which of Doc 9303’s alternative recommendations to use where Table A offers more than one.
- Zone
Field - A field
apply_occlusioncan report as withheld: exactly the fields no ICAO 9303 check digit covers on any of the five formats (mrz’s own “What a passing parse guarantees” table names the same set as unverifiable).#[non_exhaustive]: a future coverage refinement (#519, #551) could narrow this further without breaking a caller’smatch.
Constants§
- CLASSES
- The ten residue classes partitioning the 37-character MRZ alphabet:
CLASSES[r]lists every character whose ICAO value is ≡r(mod 10). - CONFUSABLES
- Bounded table of OCR glyph confusions,
(character, confusable-with). - CURRENT_
YY - The default two-digit-year pivot (2026). Birth years greater than this map to the 1900s.
- MRZ_
ALPHABET - The 37-character ICAO 9303 MRZ alphabet, in the order the solver sweeps it.
- UNKNOWN
- 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.
Functions§
- alternate_
names - Every
(name, code)pairALTERNATE_NAMESholds, in table order —codes’s sibling accessor for the fallback tablecode_for_nameconsults afterCODESitself declines. - apply_
occlusion - Apply an image-derived
CellMaskto a zoneMrzDataalready parsed. - blindspot
- Classify a single-character substitution: can any ICAO check digit tell
afromb? - check_
digit - Compute the ICAO 9303 check digit (part 3 §4.9: 7-3-1 repeating weights, mod 10).
- class_
of - The residue class
cbelongs to, as a borrowed row ofCLASSES, orNonewhencis outside the MRZ alphabet. Allocation-free. - code_
for_ name - Map a country or entity name back to its ICAO/ISO 3166-1 code —
the reverse of
country_name, over the sameCODEStable 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"). ReturnsNonefor names not in the table; when a name has more than one legitimate code (Kosovo, Germany — seeCODES’s doc comment), the first code in table order wins (XKXfor Kosovo,DEUfor Germany). - codes
- Every
(code, name)paircountry_nameandcode_for_nameare built on, in table order. - codes_
equivalent - Whether two ICAO/ISO 3166-1 codes name the same country or entity.
- collisions
- Every MRZ character a check digit cannot distinguish from
c, excludingcitself. Empty whencis outside the alphabet. - country_
name - Map an ICAO/ISO 3166-1 code (usually three letters; ICAO
Dis one) to a country or entity name. ReturnsNonefor codes not in the table. - date_
completeness - Classify a raw six-character MRZ
YYMMDDdate field. - encode_
name_ component - ICAO 9303 §4.6 encoding of one name component (a surname half or a given-
names half), as it would be printed into an MRZ name field: uppercased,
transliterated, apostrophes dropped with no filler, hyphens/commas/spaces
folded to a single
<. - expand_
date - Expand
YYMMDDto ISOYYYY-MM-DD. - expand_
date_ with_ pivot - Like
expand_datebut with a caller-supplied two-digit-year pivot. - find_
and_ parse - Scan free-form text (e.g. OCR output) for an MRZ and parse it.
- find_
and_ parse_ with find_and_parsewith an explicitParseOptions.- format_
mrv_ a - Emit an MRV-A (machine readable visa) MRZ: two 44-character lines joined
by
\n. - format_
mrv_ b - Emit an MRV-B (machine readable visa) MRZ: two 36-character lines joined
by
\n. - format_
td1 - Emit a TD1 (ID-card) MRZ: three 30-character lines joined by
\n. - format_
td2 - Emit a TD2 (identity-card) MRZ: two 36-character lines joined by
\n. - format_
td3 - Emit a TD3 (passport) MRZ: two 44-character lines joined by
\n. - is_
leap_ year - Gregorian leap-year rule: divisible by 4, except century years, which must also be divisible by 400 (so 2000 is a leap year but 1900 is not).
- parse_
mrv_ a - Parse an MRV-A machine readable visa: two lines of exactly 44 characters (ICAO 9303 part 7). Geometry mirrors TD3 through the expiry check digit, but there is no personal-number field and no composite check digit.
- parse_
mrv_ a_ with parse_mrv_awith an explicitParseOptions— pin the two-digit-year pivot instead of inheritingCURRENT_YY.- parse_
mrv_ b - Parse an MRV-B machine readable visa: two lines of exactly 36 characters (ICAO 9303 part 7). Geometry mirrors TD2 through the expiry check digit, but there is no personal-number field and no composite check digit.
- parse_
mrv_ b_ with parse_mrv_bwith an explicitParseOptions— pin the two-digit-year pivot instead of inheritingCURRENT_YY.- parse_
td1 - Parse a TD1 (ID card) MRZ: three lines of exactly 30 characters (ICAO 9303 part 5).
- parse_
td2 - Parse a TD2 MRZ: two lines of exactly 36 characters (ICAO 9303 part 6).
Covers identity-card document codes (
I/A/C); MRV-B visas share the geometry but lack a composite check digit and are not handled here. - parse_
td3 - Parse a TD3 (passport) MRZ: two lines of exactly 44 characters (ICAO 9303 part 4 §4.2.2). Long-document-number overflow is decoded here too, though Part 4 defines no such rule for TD3 — it is applied by analogy to part 5 note j / part 6 note j, because issuers do it in practice.
- parse_
td1_ with parse_td1with an explicitParseOptions— pin the two-digit-year pivot instead of inheritingCURRENT_YY.- parse_
td2_ with parse_td2with an explicitParseOptions— pin the two-digit-year pivot instead of inheritingCURRENT_YY.- parse_
td3_ with parse_td3with an explicitParseOptions— pin the two-digit-year pivot instead of inheritingCURRENT_YY.- passport_
type - Looks up a document code against the §4.4 table.
- select_
line1 - Look in
text, the OCR textfind_and_parse_withreadacceptedfrom, for a better line 1 thanaccepted’s, and report the verdict. - solve_
class_ sweep - Every way one confusable class could be swept uniformly across
fieldand its own check-digit cell. - solve_
field - Resolve the
UNKNOWNpositions in one check-digited field. - solve_
substitution - Resolve a field that is the right width but may carry one misread glyph.
- substitution_
candidates - Every single-glyph substitution of
fieldunderCONFUSABLES. - transliterate
- Uppercase
sand replace every Table A character with itsstyletransliteration. Characters outside Table A pass through unchanged (uppercased). This performs no MRZ filler handling and no truncation. - transliterate_
char - The single transliteration for
cunderstyle, orNoneifcis not in Table A. - transliterate_
cyrillic - Upper-case
sand transliterate every Cyrillic character per ICAO 9303 Part 3 §6 B, usinglang’s column. The first character ofsis the “first character” for the five Ukrainian positional rows. - transliterate_
cyrillic_ char - The §6 B transliteration of a single upper-case Cyrillic character, or
Noneifcis not one of the 48 §6 B code points.langselects the twelve language-conditional rows;is_first(whethercis the first character of the name) applies the five “Ukrainian first character” positional rows. - transliterations
- Every ICAO-recommended transliteration for
c, in the order Doc 9303 lists them. Empty ifcis not in Table A. - verify
- Verify
fieldagainst its printed check digit character. A<check digit counts as 0; ICAO permits it for an unused TD3 personal number (Part 4 §4.2.2.2). - width_
candidates - Every way
linecould be restored to exactlytargetcharacters.