Skip to main content

opencitations_client/
date.rs

1//! The two time-shaped fields OpenCitations writes, both as strings.
2//!
3//! A publication date is only as precise as the publisher recorded it, and the
4//! interval between two of them is an ISO-8601 duration rather than a number of
5//! days, because you cannot subtract `2024` from `2024-04` and get one.
6
7use serde::{Deserialize, Serialize};
8use std::fmt;
9use std::str::FromStr;
10
11/// A publication date, to whatever precision it was recorded at.
12///
13/// `2022`, `2022-01` and `2022-01-15` are all dates OpenCitations answers with,
14/// and the missing parts are genuinely unknown rather than the first of the
15/// month -- which is why this is not a `NaiveDate`.
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
17pub struct PartialDate {
18    year: i32,
19    month: Option<u8>,
20    day: Option<u8>,
21}
22
23/// Why a string is not a [`PartialDate`].
24#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
25#[error("`{given}` is not a date: {why}")]
26pub struct DateParseError {
27    /// the string as it was written
28    pub given: String,
29    /// what is wrong with it
30    pub why: &'static str,
31}
32
33impl PartialDate {
34    /// The year, the one part always present.
35    pub fn year(&self) -> i32 {
36        self.year
37    }
38
39    /// The month, when it was recorded.
40    pub fn month(&self) -> Option<u8> {
41        self.month
42    }
43
44    /// The day, when it was recorded.
45    pub fn day(&self) -> Option<u8> {
46        self.day
47    }
48}
49
50impl FromStr for PartialDate {
51    type Err = DateParseError;
52
53    fn from_str(date: &str) -> Result<Self, Self::Err> {
54        let date = date.trim();
55        let bad = |why| DateParseError {
56            given: date.to_string(),
57            why,
58        };
59
60        let mut parts = date.split('-');
61        let year = parts
62            .next()
63            .filter(|year| !year.is_empty())
64            .ok_or_else(|| bad("it has no year"))?
65            .parse()
66            .map_err(|_| bad("its year is not a number"))?;
67
68        let mut next = |what, max| match parts.next() {
69            None => Ok(None),
70            Some(part) => match part.parse::<u8>() {
71                Ok(value) if (1..=max).contains(&value) => Ok(Some(value)),
72                _ => Err(bad(what)),
73            },
74        };
75        let month = next("its month is not a month", 12)?;
76        let day = next("its day is not a day", 31)?;
77
78        if parts.next().is_some() {
79            return Err(bad("it has more parts than a date has"));
80        }
81        // `2024--15` would otherwise pass as a year with a day and no month
82        if day.is_some() && month.is_none() {
83            return Err(bad("it has a day but no month"));
84        }
85
86        Ok(PartialDate { year, month, day })
87    }
88}
89
90impl fmt::Display for PartialDate {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "{:04}", self.year)?;
93        if let Some(month) = self.month {
94            write!(f, "-{month:02}")?;
95            if let Some(day) = self.day {
96                write!(f, "-{day:02}")?;
97            }
98        }
99        Ok(())
100    }
101}
102
103/// How long after the cited work the citing work was published, as OpenCitations
104/// measures it.
105///
106/// An ISO-8601 duration in years, months and days -- `P2Y3M` is two years and
107/// three months. It is **negative** when the citing work was published first,
108/// which happens more often than it sounds: a preprint cited before its version
109/// of record appeared, or a reference added to a work whose recorded date never
110/// moved.
111#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
112pub struct Timespan {
113    negative: bool,
114    years: u32,
115    months: u32,
116    days: u32,
117}
118
119/// Why a string is not a [`Timespan`].
120#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
121#[error("`{given}` is not an iso-8601 duration: {why}")]
122pub struct TimespanParseError {
123    /// the string as it was written
124    pub given: String,
125    /// what is wrong with it
126    pub why: &'static str,
127}
128
129impl Timespan {
130    /// Whether the citing work was published *before* the cited one.
131    pub fn is_negative(&self) -> bool {
132        self.negative
133    }
134
135    /// The years component.
136    pub fn years(&self) -> u32 {
137        self.years
138    }
139
140    /// The months component.
141    pub fn months(&self) -> u32 {
142        self.months
143    }
144
145    /// The days component.
146    pub fn days(&self) -> u32 {
147        self.days
148    }
149
150    /// The span in whole months, negative when the citing work came first.
151    ///
152    /// Days are dropped rather than rounded, because the dates they were
153    /// derived from are frequently no more precise than a month anyway.
154    pub fn as_months(&self) -> i64 {
155        let months = i64::from(self.years) * 12 + i64::from(self.months);
156        if self.negative { -months } else { months }
157    }
158}
159
160impl FromStr for Timespan {
161    type Err = TimespanParseError;
162
163    fn from_str(span: &str) -> Result<Self, Self::Err> {
164        let span = span.trim();
165        let bad = |why| TimespanParseError {
166            given: span.to_string(),
167            why,
168        };
169
170        let (negative, rest) = match span.strip_prefix('-') {
171            Some(rest) => (true, rest),
172            None => (false, span),
173        };
174        let rest = rest.strip_prefix('P').ok_or_else(|| bad("it has no `P`"))?;
175
176        let mut parsed = Timespan {
177            negative,
178            ..Default::default()
179        };
180        let mut digits = String::new();
181        let mut seen = 0u8;
182
183        for c in rest.chars() {
184            if c.is_ascii_digit() {
185                digits.push(c);
186                continue;
187            }
188            // `PT1H` and the rest of the time half never appear in a citation
189            // timespan, and guessing at one would put an hour where a year goes
190            let unit = match c {
191                'Y' => &mut parsed.years,
192                'M' => &mut parsed.months,
193                'D' => &mut parsed.days,
194                _ => return Err(bad("it has a unit that is not Y, M or D")),
195            };
196            *unit = digits
197                .parse()
198                .map_err(|_| bad("a component has no number in front of its unit"))?;
199            digits.clear();
200            seen += 1;
201        }
202
203        if !digits.is_empty() {
204            return Err(bad("a component has no unit after its number"));
205        }
206        if seen == 0 {
207            return Err(bad("it names no years, months or days"));
208        }
209
210        Ok(parsed)
211    }
212}
213
214impl fmt::Display for Timespan {
215    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
216        if self.negative {
217            f.write_str("-")?;
218        }
219        f.write_str("P")?;
220        // `P0D` rather than a bare `P`, which is not a duration
221        if self.years == 0 && self.months == 0 && self.days == 0 {
222            return f.write_str("0D");
223        }
224        if self.years > 0 {
225            write!(f, "{}Y", self.years)?;
226        }
227        if self.months > 0 {
228            write!(f, "{}M", self.months)?;
229        }
230        if self.days > 0 {
231            write!(f, "{}D", self.days)?;
232        }
233        Ok(())
234    }
235}
236
237macro_rules! serde_via_string {
238    ($($ty:ty),*) => {$(
239        impl Serialize for $ty {
240            fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
241                serializer.collect_str(self)
242            }
243        }
244
245        impl<'de> Deserialize<'de> for $ty {
246            fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
247                let raw = String::deserialize(deserializer)?;
248                raw.parse().map_err(serde::de::Error::custom)
249            }
250        }
251    )*};
252}
253
254serde_via_string!(PartialDate, Timespan);
255
256#[cfg(test)]
257mod tests {
258    use super::*;
259
260    #[test]
261    fn a_date_keeps_the_precision_it_was_written_at() {
262        let year: PartialDate = "2022".parse().unwrap();
263        assert_eq!((year.year(), year.month(), year.day()), (2022, None, None));
264        assert_eq!(year.to_string(), "2022");
265
266        let month: PartialDate = "2022-01".parse().unwrap();
267        assert_eq!(month.month(), Some(1));
268        assert_eq!(month.day(), None);
269        assert_eq!(month.to_string(), "2022-01");
270
271        let day: PartialDate = "2022-01-15".parse().unwrap();
272        assert_eq!(day.day(), Some(15));
273        assert_eq!(day.to_string(), "2022-01-15");
274    }
275
276    #[test]
277    fn something_that_is_not_a_date_is_refused() {
278        for bad in [
279            "",
280            "not-a-year",
281            "2022-13",
282            "2022-01-32",
283            "2022-01-15-01",
284            "2022--15",
285        ] {
286            assert!(bad.parse::<PartialDate>().is_err(), "`{bad}` parsed");
287        }
288    }
289
290    #[test]
291    fn a_timespan_reads_its_components() {
292        let span: Timespan = "P2Y3M".parse().unwrap();
293        assert_eq!((span.years(), span.months(), span.days()), (2, 3, 0));
294        assert!(!span.is_negative());
295        assert_eq!(span.as_months(), 27);
296        assert_eq!(span.to_string(), "P2Y3M");
297
298        let days: Timespan = "P0D".parse().unwrap();
299        assert_eq!(days.as_months(), 0);
300        assert_eq!(days.to_string(), "P0D");
301    }
302
303    /// A citing work can predate the work it cites -- a preprint cited before
304    /// its version of record was published is the common way.
305    #[test]
306    fn a_negative_timespan_says_the_citing_work_came_first() {
307        let span: Timespan = "-P1Y2M".parse().unwrap();
308        assert!(span.is_negative());
309        assert_eq!(span.as_months(), -14);
310        assert_eq!(span.to_string(), "-P1Y2M");
311    }
312
313    #[test]
314    fn something_that_is_not_a_duration_is_refused() {
315        for bad in ["", "2Y", "P", "PY", "P1H", "P1Y2", "PT1H"] {
316            assert!(bad.parse::<Timespan>().is_err(), "`{bad}` parsed");
317        }
318    }
319}