use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PartialDate {
year: i32,
month: Option<u8>,
day: Option<u8>,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{given}` is not a date: {why}")]
pub struct DateParseError {
pub given: String,
pub why: &'static str,
}
impl PartialDate {
pub fn year(&self) -> i32 {
self.year
}
pub fn month(&self) -> Option<u8> {
self.month
}
pub fn day(&self) -> Option<u8> {
self.day
}
}
impl FromStr for PartialDate {
type Err = DateParseError;
fn from_str(date: &str) -> Result<Self, Self::Err> {
let date = date.trim();
let bad = |why| DateParseError {
given: date.to_string(),
why,
};
let mut parts = date.split('-');
let year = parts
.next()
.filter(|year| !year.is_empty())
.ok_or_else(|| bad("it has no year"))?
.parse()
.map_err(|_| bad("its year is not a number"))?;
let mut next = |what, max| match parts.next() {
None => Ok(None),
Some(part) => match part.parse::<u8>() {
Ok(value) if (1..=max).contains(&value) => Ok(Some(value)),
_ => Err(bad(what)),
},
};
let month = next("its month is not a month", 12)?;
let day = next("its day is not a day", 31)?;
if parts.next().is_some() {
return Err(bad("it has more parts than a date has"));
}
if day.is_some() && month.is_none() {
return Err(bad("it has a day but no month"));
}
Ok(PartialDate { year, month, day })
}
}
impl fmt::Display for PartialDate {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{:04}", self.year)?;
if let Some(month) = self.month {
write!(f, "-{month:02}")?;
if let Some(day) = self.day {
write!(f, "-{day:02}")?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Timespan {
negative: bool,
years: u32,
months: u32,
days: u32,
}
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{given}` is not an iso-8601 duration: {why}")]
pub struct TimespanParseError {
pub given: String,
pub why: &'static str,
}
impl Timespan {
pub fn is_negative(&self) -> bool {
self.negative
}
pub fn years(&self) -> u32 {
self.years
}
pub fn months(&self) -> u32 {
self.months
}
pub fn days(&self) -> u32 {
self.days
}
pub fn as_months(&self) -> i64 {
let months = i64::from(self.years) * 12 + i64::from(self.months);
if self.negative { -months } else { months }
}
}
impl FromStr for Timespan {
type Err = TimespanParseError;
fn from_str(span: &str) -> Result<Self, Self::Err> {
let span = span.trim();
let bad = |why| TimespanParseError {
given: span.to_string(),
why,
};
let (negative, rest) = match span.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, span),
};
let rest = rest.strip_prefix('P').ok_or_else(|| bad("it has no `P`"))?;
let mut parsed = Timespan {
negative,
..Default::default()
};
let mut digits = String::new();
let mut seen = 0u8;
for c in rest.chars() {
if c.is_ascii_digit() {
digits.push(c);
continue;
}
let unit = match c {
'Y' => &mut parsed.years,
'M' => &mut parsed.months,
'D' => &mut parsed.days,
_ => return Err(bad("it has a unit that is not Y, M or D")),
};
*unit = digits
.parse()
.map_err(|_| bad("a component has no number in front of its unit"))?;
digits.clear();
seen += 1;
}
if !digits.is_empty() {
return Err(bad("a component has no unit after its number"));
}
if seen == 0 {
return Err(bad("it names no years, months or days"));
}
Ok(parsed)
}
}
impl fmt::Display for Timespan {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.negative {
f.write_str("-")?;
}
f.write_str("P")?;
if self.years == 0 && self.months == 0 && self.days == 0 {
return f.write_str("0D");
}
if self.years > 0 {
write!(f, "{}Y", self.years)?;
}
if self.months > 0 {
write!(f, "{}M", self.months)?;
}
if self.days > 0 {
write!(f, "{}D", self.days)?;
}
Ok(())
}
}
macro_rules! serde_via_string {
($($ty:ty),*) => {$(
impl Serialize for $ty {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_str(self)
}
}
impl<'de> Deserialize<'de> for $ty {
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
let raw = String::deserialize(deserializer)?;
raw.parse().map_err(serde::de::Error::custom)
}
}
)*};
}
serde_via_string!(PartialDate, Timespan);
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_date_keeps_the_precision_it_was_written_at() {
let year: PartialDate = "2022".parse().unwrap();
assert_eq!((year.year(), year.month(), year.day()), (2022, None, None));
assert_eq!(year.to_string(), "2022");
let month: PartialDate = "2022-01".parse().unwrap();
assert_eq!(month.month(), Some(1));
assert_eq!(month.day(), None);
assert_eq!(month.to_string(), "2022-01");
let day: PartialDate = "2022-01-15".parse().unwrap();
assert_eq!(day.day(), Some(15));
assert_eq!(day.to_string(), "2022-01-15");
}
#[test]
fn something_that_is_not_a_date_is_refused() {
for bad in [
"",
"not-a-year",
"2022-13",
"2022-01-32",
"2022-01-15-01",
"2022--15",
] {
assert!(bad.parse::<PartialDate>().is_err(), "`{bad}` parsed");
}
}
#[test]
fn a_timespan_reads_its_components() {
let span: Timespan = "P2Y3M".parse().unwrap();
assert_eq!((span.years(), span.months(), span.days()), (2, 3, 0));
assert!(!span.is_negative());
assert_eq!(span.as_months(), 27);
assert_eq!(span.to_string(), "P2Y3M");
let days: Timespan = "P0D".parse().unwrap();
assert_eq!(days.as_months(), 0);
assert_eq!(days.to_string(), "P0D");
}
#[test]
fn a_negative_timespan_says_the_citing_work_came_first() {
let span: Timespan = "-P1Y2M".parse().unwrap();
assert!(span.is_negative());
assert_eq!(span.as_months(), -14);
assert_eq!(span.to_string(), "-P1Y2M");
}
#[test]
fn something_that_is_not_a_duration_is_refused() {
for bad in ["", "2Y", "P", "PY", "P1H", "P1Y2", "PT1H"] {
assert!(bad.parse::<Timespan>().is_err(), "`{bad}` parsed");
}
}
}