opencitations-client 0.1.0

An async Rust client for the OpenCitations Index and Meta REST APIs
Documentation
//! The two time-shaped fields OpenCitations writes, both as strings.
//!
//! A publication date is only as precise as the publisher recorded it, and the
//! interval between two of them is an ISO-8601 duration rather than a number of
//! days, because you cannot subtract `2024` from `2024-04` and get one.

use serde::{Deserialize, Serialize};
use std::fmt;
use std::str::FromStr;

/// A publication date, to whatever precision it was recorded at.
///
/// `2022`, `2022-01` and `2022-01-15` are all dates OpenCitations answers with,
/// and the missing parts are genuinely unknown rather than the first of the
/// month -- which is why this is not a `NaiveDate`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PartialDate {
    year: i32,
    month: Option<u8>,
    day: Option<u8>,
}

/// Why a string is not a [`PartialDate`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{given}` is not a date: {why}")]
pub struct DateParseError {
    /// the string as it was written
    pub given: String,
    /// what is wrong with it
    pub why: &'static str,
}

impl PartialDate {
    /// The year, the one part always present.
    pub fn year(&self) -> i32 {
        self.year
    }

    /// The month, when it was recorded.
    pub fn month(&self) -> Option<u8> {
        self.month
    }

    /// The day, when it was recorded.
    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"));
        }
        // `2024--15` would otherwise pass as a year with a day and no month
        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(())
    }
}

/// How long after the cited work the citing work was published, as OpenCitations
/// measures it.
///
/// An ISO-8601 duration in years, months and days -- `P2Y3M` is two years and
/// three months. It is **negative** when the citing work was published first,
/// which happens more often than it sounds: a preprint cited before its version
/// of record appeared, or a reference added to a work whose recorded date never
/// moved.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Timespan {
    negative: bool,
    years: u32,
    months: u32,
    days: u32,
}

/// Why a string is not a [`Timespan`].
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[error("`{given}` is not an iso-8601 duration: {why}")]
pub struct TimespanParseError {
    /// the string as it was written
    pub given: String,
    /// what is wrong with it
    pub why: &'static str,
}

impl Timespan {
    /// Whether the citing work was published *before* the cited one.
    pub fn is_negative(&self) -> bool {
        self.negative
    }

    /// The years component.
    pub fn years(&self) -> u32 {
        self.years
    }

    /// The months component.
    pub fn months(&self) -> u32 {
        self.months
    }

    /// The days component.
    pub fn days(&self) -> u32 {
        self.days
    }

    /// The span in whole months, negative when the citing work came first.
    ///
    /// Days are dropped rather than rounded, because the dates they were
    /// derived from are frequently no more precise than a month anyway.
    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;
            }
            // `PT1H` and the rest of the time half never appear in a citation
            // timespan, and guessing at one would put an hour where a year goes
            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")?;
        // `P0D` rather than a bare `P`, which is not a duration
        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");
    }

    /// A citing work can predate the work it cites -- a preprint cited before
    /// its version of record was published is the common way.
    #[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");
        }
    }
}