use winnow::{stream::AsChar, token::take_while, ModalResult, Parser};
use super::primitive::s;
pub(super) fn year_from_str(year_str: &str) -> Result<u16, &'static str> {
let mut year = year_str
.parse::<u16>()
.map_err(|_| "year must be a valid u16 number")?;
if year_str.len() == 2 {
if year <= 68 {
year += 2000
} else {
year += 1900
}
}
if year > 9999 {
return Err("year must be no greater than 9999");
}
Ok(year)
}
pub(super) fn year_str<'a>(input: &mut &'a str) -> ModalResult<&'a str> {
s(take_while(1.., AsChar::is_dec_digit)).parse_next(input)
}
#[cfg(test)]
mod tests {
use super::year_from_str;
#[test]
fn test_year() {
assert_eq!(year_from_str("10").unwrap(), 2010u16);
assert_eq!(year_from_str("68").unwrap(), 2068u16);
assert_eq!(year_from_str("69").unwrap(), 1969u16);
assert_eq!(year_from_str("99").unwrap(), 1999u16);
assert_eq!(year_from_str("468").unwrap(), 468u16);
assert_eq!(year_from_str("469").unwrap(), 469u16);
assert_eq!(year_from_str("1568").unwrap(), 1568u16);
assert_eq!(year_from_str("1569").unwrap(), 1569u16);
assert!(year_from_str("10000").is_err());
}
}