Skip to main content

Crate mrz

Crate mrz 

Source
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 verified

parse_td1, parse_td2, parse_mrv_a and parse_mrv_b cover the other formats.

§Where to start

You haveReach for
MRZ lines, already separatedparse_td3, parse_td2, parse_td1, parse_mrv_a, parse_mrv_b
Free-form OCR textfind_and_parse — finds the zone, repairs it only under check-digit agreement
Fields to print as an MRZformat_td3 and its siblings, fed by Td3Fields and friends
A name in a national scripttransliterate (Doc 9303 Part 3 §6 A, Latin), transliterate_cyrillic (§6 B, Cyrillic), encode_name_component
A number too long for its fieldMrzData::full_document_number
A parsed record to judgeMrzData::valid for the read, MrzData::validity for the document’s dates
A glyph the OCR could not readsolve_field, solve_substitution, and Blindspot for what no check digit can catch
Cells an image shows as coveredapply_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:

§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 scanner
  • occlusion — 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 encoding
  • checksum — check-digit math and OCR line normalization
  • repair — check-digit-guided recovery of damaged or misread fields
  • blindspot — the substitutions check digits provably cannot catch
  • dates — YYMMDD expansion, the calendar, and date plausibility
  • countries — a subset of Part 3 §5 state and organization codes
  • doccode — Part 4 §4.4 secondary passport document codes
  • translit — Part 3 §6 A (Latin) and §6 B (Cyrillic) transliteration

Structs§

CellMask
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::validity and to measure days-until-expiry.
DateValidity
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.
InvalidRawDateField
Rejection from RawDateField::try_from: the text was not exactly six characters of the MRZ alphabet (0-9, A-Z, <).
Line1Selection
What select_line1 found. Off by default in every caller in this workspace.
MrvAFields
Raw MRV-A sub-fields, in MRZ-native form — the same input conventions as Td3Fields.
MrvBFields
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.
ParseMrzDateError
Rejection from parsing an MrzDate’s text form.
ParseOptions
Tunables for the parsing entry points.
ParseSexError
Rejection from parsing a Sex’s text form: it is exactly one MRZ-alphabet character.
RawDateField
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.
CyrillicLanguage
Which language’s ICAO 9303 Part 3 §6 B column to apply.
DateCompleteness
How much of a six-character MRZ date field is actually known.
DateRole
Which date a field holds, which decides the century of a two-digit year.
Field
Which check-digit-bearing field an error refers to.
FieldKind
Which ICAO field a solve_field call is resolving. Selects the structural constraint applied after the check digit, never instead of it.
Format
Which ICAO 9303 layout a zone uses.
Line1Unresolved
Why select_line1 left a zone Unresolved: which of find_and_parse_with’s wrong-physical-line checks flagged it.
Line1Verdict
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 through Checks instead of an error.
PassportType
The passport type a §4.4 secondary document code designates.
Resolution
What the check digit could prove about a field carrying UNKNOWNs.
SequenceCompleteness
A single completeness signal spanning both outcomes of a find_and_parse attempt.
Sex
What the MRZ sex cell holds.
TransliterationStyle
Which of Doc 9303’s alternative recommendations to use where Table A offers more than one.
ZoneField
A field apply_occlusion can 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’s match.

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) pair ALTERNATE_NAMES holds, in table order — codes’s sibling accessor for the fallback table code_for_name consults after CODES itself declines.
apply_occlusion
Apply an image-derived CellMask to a zone MrzData already parsed.
blindspot
Classify a single-character substitution: can any ICAO check digit tell a from b?
check_digit
Compute the ICAO 9303 check digit (part 3 §4.9: 7-3-1 repeating weights, mod 10).
class_of
The residue class c belongs to, as a borrowed row of CLASSES, or None when c is 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 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).
codes
Every (code, name) pair country_name and code_for_name are 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, excluding c itself. Empty when c is outside the alphabet.
country_name
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.
date_completeness
Classify a raw six-character MRZ YYMMDD date 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 YYMMDD to ISO YYYY-MM-DD.
expand_date_with_pivot
Like expand_date but 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_parse with an explicit ParseOptions.
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_a with an explicit ParseOptions — pin the two-digit-year pivot instead of inheriting CURRENT_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_b with an explicit ParseOptions — pin the two-digit-year pivot instead of inheriting CURRENT_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_td1 with an explicit ParseOptions — pin the two-digit-year pivot instead of inheriting CURRENT_YY.
parse_td2_with
parse_td2 with an explicit ParseOptions — pin the two-digit-year pivot instead of inheriting CURRENT_YY.
parse_td3_with
parse_td3 with an explicit ParseOptions — pin the two-digit-year pivot instead of inheriting CURRENT_YY.
passport_type
Looks up a document code against the §4.4 table.
select_line1
Look in text, the OCR text find_and_parse_with read accepted from, for a better line 1 than accepted’s, and report the verdict.
solve_class_sweep
Every way one confusable class could be swept uniformly across field and its own check-digit cell.
solve_field
Resolve the UNKNOWN positions 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 field under CONFUSABLES.
transliterate
Uppercase s and replace every Table A character with its style transliteration. Characters outside Table A pass through unchanged (uppercased). This performs no MRZ filler handling and no truncation.
transliterate_char
The single transliteration for c under style, or None if c is not in Table A.
transliterate_cyrillic
Upper-case s and transliterate every Cyrillic character per ICAO 9303 Part 3 §6 B, using lang’s column. The first character of s is the “first character” for the five Ukrainian positional rows.
transliterate_cyrillic_char
The §6 B transliteration of a single upper-case Cyrillic character, or None if c is not one of the 48 §6 B code points. lang selects the twelve language-conditional rows; is_first (whether c is 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 if c is not in Table A.
verify
Verify field against its printed check digit character. A < check digit counts as 0; ICAO permits it for an unused TD3 personal number (Part 4 §4.2.2.2).
width_candidates
Every way line could be restored to exactly target characters.