#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
pub fn expand_date(yymmdd: &str, is_birth: bool) -> String {
expand_date_with_pivot(yymmdd, is_birth, CURRENT_YY)
}
pub const CURRENT_YY: u32 = 26;
pub fn expand_date_with_pivot(yymmdd: &str, is_birth: bool, pivot_yy: u32) -> String {
if yymmdd.len() != 6 || !yymmdd.chars().all(|c| c.is_ascii_digit()) {
return yymmdd.to_string(); }
let yy: u32 = yymmdd[0..2].parse().unwrap();
let century = century_for(yy, is_birth, pivot_yy) / 100;
format!(
"{century}{}-{}-{}",
&yymmdd[0..2],
&yymmdd[2..4],
&yymmdd[4..6]
)
}
pub(crate) fn century_for(yy: u32, is_birth: bool, pivot_yy: u32) -> i32 {
if is_birth && yy > pivot_yy {
1900
} else {
2000
}
}
pub fn is_leap_year(year: i32) -> bool {
year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
pub enum DateCompleteness {
#[default]
Complete,
PartiallyUnknown,
Unknown,
Malformed,
}
pub fn date_completeness(yymmdd: &str) -> DateCompleteness {
if yymmdd.len() != 6 {
return DateCompleteness::Malformed;
}
let digits = yymmdd.chars().filter(|c| c.is_ascii_digit()).count();
let fillers = yymmdd.chars().filter(|&c| c == '<').count();
if digits + fillers != yymmdd.len() {
return DateCompleteness::Malformed;
}
match (digits, fillers) {
(6, 0) => DateCompleteness::Complete,
(0, 6) => DateCompleteness::Unknown,
_ => DateCompleteness::PartiallyUnknown,
}
}
fn days_in_month(year: i32, month: u32) -> u32 {
match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => {
if is_leap_year(year) {
29
} else {
28
}
}
_ => 0,
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct Date {
pub year: i32,
pub month: u32,
pub day: u32,
}
impl Date {
pub fn new(year: i32, month: u32, day: u32) -> Self {
Self { year, month, day }
}
pub fn is_well_formed(self) -> bool {
(1..=12).contains(&self.month)
&& (1..=days_in_month(self.year, self.month)).contains(&self.day)
}
pub fn to_epoch_days(self) -> i64 {
let y = if self.month <= 2 {
self.year - 1
} else {
self.year
} as i64;
let m = self.month as i64;
let d = self.day as i64;
let era = (if y >= 0 { y } else { y - 399 }) / 400;
let yoe = y - era * 400; let doy = (153 * (if m > 2 { m - 3 } else { m + 9 }) + 2) / 5 + d - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146097 + doe - 719468
}
pub fn from_epoch_days(days: i64) -> Date {
let z = days + 719468;
let era = (if z >= 0 { z } else { z - 146096 }) / 146097;
let doe = z - era * 146097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = doy - (153 * mp + 2) / 5 + 1; let m = if mp < 10 { mp + 3 } else { mp - 9 }; Date {
year: (y + i64::from(m <= 2)) as i32,
month: m as u32,
day: d as u32,
}
}
}
#[cfg(feature = "zeroize")]
#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
impl zeroize::Zeroize for Date {
fn zeroize(&mut self) {
self.year.zeroize();
self.month.zeroize();
self.day.zeroize();
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
#[non_exhaustive]
pub struct DateValidity {
pub dates_well_formed: bool,
pub in_date: bool,
pub dob_before_expiry: bool,
pub days_until_expiry: Option<i64>,
}
impl DateValidity {
pub fn all_ok(&self) -> bool {
self.dates_well_formed && self.in_date && self.dob_before_expiry
}
}
impl crate::MrzData {
pub fn validity(&self, today: Date) -> DateValidity {
let dob = self.date_of_birth.calendar();
let exp = self.date_of_expiry.calendar();
let (in_date, days_until_expiry) = match exp {
Some(e) => {
let days = e.to_epoch_days() - today.to_epoch_days();
(days >= 0, Some(days))
}
None => (false, None),
};
let dob_before_expiry = matches!(
(dob, exp),
(Some(b), Some(e)) if b.to_epoch_days() < e.to_epoch_days()
);
DateValidity {
dates_well_formed: dob.is_some() && exp.is_some(),
in_date,
dob_before_expiry,
days_until_expiry,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::parse_td3;
use proptest::prelude::*;
const TD3_L1: &str = "P<UTOERIKSSON<<ANNA<MARIA<<<<<<<<<<<<<<<<<<<";
const TD3_L2: &str = "L898902C36UTO7408122F1204159ZE184226B<<<<<10";
#[test]
fn date_completeness_classifies_all_five_cases() {
assert_eq!(date_completeness("740812"), DateCompleteness::Complete);
assert_eq!(date_completeness("<<<<<<"), DateCompleteness::Unknown);
assert_eq!(
date_completeness("74<<12"),
DateCompleteness::PartiallyUnknown
);
assert_eq!(date_completeness(""), DateCompleteness::Malformed);
assert_eq!(date_completeness("74081"), DateCompleteness::Malformed); assert_eq!(date_completeness("7408122"), DateCompleteness::Malformed); assert_eq!(date_completeness("7X0812"), DateCompleteness::Malformed);
}
#[test]
fn date_century_pivot() {
assert_eq!(expand_date("740812", true), "1974-08-12");
assert_eq!(expand_date("150101", true), "2015-01-01");
assert_eq!(expand_date("301231", false), "2030-12-31");
}
#[test]
fn century_pivot_boundary() {
assert_eq!(expand_date("260101", true), "2026-01-01");
assert_eq!(expand_date("270101", true), "1927-01-01");
assert_eq!(expand_date("990101", true), "1999-01-01");
assert_eq!(expand_date("270101", false), "2027-01-01");
}
#[test]
fn leap_year_rule() {
assert!(is_leap_year(2000));
assert!(!is_leap_year(1900));
assert!(is_leap_year(2024));
assert!(!is_leap_year(2023));
}
#[test]
fn is_well_formed_rejects_impossible_calendar_dates() {
assert!(Date::new(2024, 2, 29).is_well_formed());
assert!(!Date::new(2023, 2, 29).is_well_formed());
assert!(!Date::new(2023, 2, 30).is_well_formed());
assert!(!Date::new(2023, 4, 31).is_well_formed());
assert!(!Date::new(2023, 6, 31).is_well_formed());
assert!(!Date::new(2023, 11, 31).is_well_formed());
assert!(Date::new(2023, 12, 31).is_well_formed());
assert!(Date::new(2023, 1, 31).is_well_formed());
assert!(!Date::new(2023, 0, 10).is_well_formed());
assert!(!Date::new(2023, 13, 1).is_well_formed());
assert!(!Date::new(2023, 1, 0).is_well_formed());
}
proptest! {
#[test]
fn is_well_formed_matches_epoch_day_round_trip(
year in 1900i32..=2100,
month in 1u32..=13,
day in 0u32..=32,
) {
let d = Date::new(year, month, day);
prop_assert_eq!(
d.is_well_formed(),
Date::from_epoch_days(d.to_epoch_days()) == d
);
}
}
#[test]
fn epoch_days_reference_points() {
assert_eq!(Date::new(1970, 1, 1).to_epoch_days(), 0);
assert_eq!(Date::new(1969, 12, 31).to_epoch_days(), -1);
assert_eq!(Date::new(2000, 1, 1).to_epoch_days(), 10957);
}
#[test]
fn epoch_days_roundtrip() {
for &(y, m, d) in &[(1970, 1, 1), (1974, 8, 12), (2012, 4, 15), (2026, 7, 17)] {
let date = Date::new(y, m, d);
assert_eq!(Date::from_epoch_days(date.to_epoch_days()), date);
}
}
#[test]
fn validity_tracks_expiry_and_consistency() {
let d = parse_td3(TD3_L1, TD3_L2).unwrap();
let before = d.validity(Date::new(2011, 1, 1));
assert!(before.dates_well_formed);
assert!(before.dob_before_expiry);
assert!(before.in_date);
assert!(before.all_ok());
let after = d.validity(Date::new(2020, 1, 1));
assert!(!after.in_date);
assert!(after.days_until_expiry.unwrap() < 0);
assert!(!after.all_ok());
}
#[test]
fn days_until_expiry_is_exact() {
let d = parse_td3(TD3_L1, TD3_L2).unwrap();
let v = d.validity(Date::new(2012, 4, 14));
assert_eq!(v.days_until_expiry, Some(1));
assert!(v.in_date);
}
}