//! Timestamps and durations as the Libby services spell them. //! //! The services mix several timestamp spellings, sometimes within a single //! response. [`parse_timestamp`] accepts exactly the spellings documented for //! the API and rejects everything else with a [`TimeError`]: a guessed date //! on a loan is worse than a loud failure, because the UI would confidently //! show the wrong due date. //! //! Accepted timestamp spellings: //! //! | Spelling | Example | //! | --- | --- | //! | UTC, whole seconds | `2023-03-31T00:00:00Z` | //! | UTC, 1–9 fractional digits | `2026-11-15T18:07:55.5931239Z` | //! | explicit offset | `2007-05-29T04:00:00+00:00`, `…-0500` | //! | US calendar date (midnight UTC) | `05/29/2007` | //! //! Durations are `H:MM:SS` with any number of hour digits (`"21:02:06"`, //! `"104:00:01"`). //! //! The `serde` helper modules ([`timestamp`], [`option_timestamp`], //! [`epoch_seconds`], [`hms`], [`option_hms`]) plug these parsers into the //! models with `#[serde(with = "…")]`. use std::time::Duration; use jiff::Timestamp; use jiff::civil::DateTime; use jiff::tz::Offset; /// A timestamp or duration string that matched none of the documented /// spellings. #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] #[error("unrecognised {kind} {input:?}: {reason}")] pub struct TimeError { /// What was being parsed (`"timestamp"` or `"duration"`). pub kind: &'static str, /// The offending input, verbatim. pub input: String, /// Why it was rejected. pub reason: &'static str, } impl TimeError { fn timestamp(input: &str, reason: &'static str) -> Self { Self { kind: "timestamp", input: input.to_owned(), reason, } } fn duration(input: &str, reason: &'static str) -> Self { Self { kind: "duration", input: input.to_owned(), reason, } } } /// Parses a timestamp in any of the documented spellings (see the module /// docs). Anything else is an error. /// /// # Errors /// /// [`TimeError`] when the input is not one of the documented spellings or /// names an impossible date or time. pub fn parse_timestamp(input: &str) -> Result { if input.contains('/') { parse_us_date(input) } else { parse_iso(input) } } /// `MM/DD/YYYY`, one or two digits for month and day, read as midnight UTC. fn parse_us_date(input: &str) -> Result { let err = |reason| TimeError::timestamp(input, reason); let mut parts = input.split('/'); let (Some(month), Some(day), Some(year), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return Err(err("expected MM/DD/YYYY")); }; let month = small_number(month, 1..=2).ok_or_else(|| err("bad month"))?; let day = small_number(day, 1..=2).ok_or_else(|| err("bad day"))?; let year = small_number(year, 4..=4).ok_or_else(|| err("bad year"))?; let date = DateTime::new(to_i16(year), to_i8(month), to_i8(day), 0, 0, 0, 0) .map_err(|_| err("no such date"))?; Offset::UTC .to_timestamp(date) .map_err(|_| err("date out of range")) } /// `YYYY-MM-DDTHH:MM:SS[.f{1,9}](Z|±HH:MM|±HHMM)`. fn parse_iso(input: &str) -> Result { let err = |reason| TimeError::timestamp(input, reason); let mut cursor = Cursor::new(input); let year = cursor.digits(4).ok_or_else(|| err("bad year"))?; cursor .expect(b'-') .ok_or_else(|| err("expected '-' after year"))?; let month = cursor.digits(2).ok_or_else(|| err("bad month"))?; cursor .expect(b'-') .ok_or_else(|| err("expected '-' after month"))?; let day = cursor.digits(2).ok_or_else(|| err("bad day"))?; cursor .expect(b'T') .ok_or_else(|| err("expected 'T' between date and time"))?; let hour = cursor.digits(2).ok_or_else(|| err("bad hour"))?; cursor.expect(b':').ok_or_else(|| err("expected ':'"))?; let minute = cursor.digits(2).ok_or_else(|| err("bad minute"))?; cursor.expect(b':').ok_or_else(|| err("expected ':'"))?; let second = cursor.digits(2).ok_or_else(|| err("bad second"))?; let mut nanos: u32 = 0; if cursor.expect(b'.').is_some() { let start = cursor.pos; let mut scale = 100_000_000; while let Some(digit) = cursor.digit() { if cursor.pos - start > 9 { return Err(err("more than 9 fractional digits")); } nanos += digit * scale; scale /= 10; } if cursor.pos == start { return Err(err("empty fraction")); } } let offset_seconds: i32 = match cursor.next() { Some(b'Z') => 0, Some(sign @ (b'+' | b'-')) => { let hours = cursor.digits(2).ok_or_else(|| err("bad offset hours"))?; // Both `+00:00` and `+0000` are in the wild. let _ = cursor.expect(b':'); let minutes = cursor.digits(2).ok_or_else(|| err("bad offset minutes"))?; if hours > 23 || minutes > 59 { return Err(err("offset out of range")); } let magnitude = i32::try_from(hours * 3600 + minutes * 60) .map_err(|_| err("offset out of range"))?; if sign == b'-' { -magnitude } else { magnitude } } Some(_) => return Err(err("expected 'Z' or an offset")), None => return Err(err("missing time zone (refusing to guess)")), }; if !cursor.is_done() { return Err(err("trailing characters")); } let datetime = DateTime::new( to_i16(year), to_i8(month), to_i8(day), to_i8(hour), to_i8(minute), to_i8(second), i32::try_from(nanos).map_err(|_| err("fraction out of range"))?, ) .map_err(|_| err("no such date or time"))?; let offset = Offset::from_seconds(offset_seconds).map_err(|_| err("offset out of range"))?; offset .to_timestamp(datetime) .map_err(|_| err("timestamp out of range")) } /// Parses an `H:MM:SS` duration. Hours may have any number of digits. /// /// # Errors /// /// [`TimeError`] when the input is not `H:MM:SS` or minutes/seconds exceed 59. pub fn parse_hms(input: &str) -> Result { let err = |reason| TimeError::duration(input, reason); let mut parts = input.split(':'); let (Some(hours), Some(minutes), Some(seconds), None) = (parts.next(), parts.next(), parts.next(), parts.next()) else { return Err(err("expected H:MM:SS")); }; let hours = small_number(hours, 1..=6).ok_or_else(|| err("bad hours"))?; let minutes = small_number(minutes, 2..=2).ok_or_else(|| err("bad minutes"))?; let seconds = small_number(seconds, 2..=2).ok_or_else(|| err("bad seconds"))?; if minutes > 59 || seconds > 59 { return Err(err("minutes or seconds out of range")); } Ok(Duration::from_secs( u64::from(hours) * 3600 + u64::from(minutes) * 60 + u64::from(seconds), )) } /// Formats a duration the way the services spell it (`H:MM:SS`), dropping /// sub-second precision. #[must_use] pub fn format_hms(duration: Duration) -> String { let total = duration.as_secs(); format!( "{}:{:02}:{:02}", total / 3600, (total / 60) % 60, total % 60 ) } /// An ASCII decimal number of an allowed digit count. Values parsed here are /// at most 6 digits, so they always fit. fn small_number(raw: &str, digits: std::ops::RangeInclusive) -> Option { if !digits.contains(&raw.len()) || !raw.bytes().all(|b| b.is_ascii_digit()) { return None; } raw.parse().ok() } // The callers bound every value to at most four digits before converting. fn to_i16(value: u32) -> i16 { i16::try_from(value).expect("a four-digit year fits in i16") } fn to_i8(value: u32) -> i8 { i8::try_from(value).expect("a two-digit field fits in i8") } /// A byte cursor over an ASCII timestamp. struct Cursor<'a> { bytes: &'a [u8], pos: usize, } impl<'a> Cursor<'a> { fn new(input: &'a str) -> Self { Self { bytes: input.as_bytes(), pos: 0, } } fn next(&mut self) -> Option { let byte = *self.bytes.get(self.pos)?; self.pos += 1; Some(byte) } fn expect(&mut self, wanted: u8) -> Option<()> { if self.bytes.get(self.pos) == Some(&wanted) { self.pos += 1; Some(()) } else { None } } fn digit(&mut self) -> Option { let byte = *self.bytes.get(self.pos)?; if byte.is_ascii_digit() { self.pos += 1; Some(u32::from(byte - b'0')) } else { None } } fn digits(&mut self, count: usize) -> Option { let mut value = 0; for _ in 0..count { value = value * 10 + self.digit()?; } Some(value) } fn is_done(&self) -> bool { self.pos == self.bytes.len() } } /// `#[serde(with = "crate::time::timestamp")]` for a required timestamp. /// Serializes as RFC 3339 in UTC, which [`parse_timestamp`] reads back. pub mod timestamp { use jiff::Timestamp; use serde::{Deserialize, Deserializer, Serializer}; /// Deserializes with [`super::parse_timestamp`]. /// /// # Errors /// /// When the value is not a string in a documented spelling. pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { let raw = String::deserialize(deserializer)?; super::parse_timestamp(&raw).map_err(serde::de::Error::custom) } /// Serializes as RFC 3339 (`2023-03-31T00:00:00Z`). /// /// # Errors /// /// Only when the serializer fails. pub fn serialize(value: &Timestamp, serializer: S) -> Result { serializer.collect_str(value) } } /// `#[serde(default, with = "crate::time::option_timestamp")]` for an optional /// timestamp. `null` and a missing field are `None`; an empty string is an /// error, because it is not one of the documented spellings. pub mod option_timestamp { use jiff::Timestamp; use serde::{Deserialize, Deserializer, Serializer}; /// Deserializes `null` as `None`, otherwise as [`super::timestamp`]. /// /// # Errors /// /// When the value is present but not a documented spelling. pub fn deserialize<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { Option::::deserialize(deserializer)? .map(|raw| super::parse_timestamp(&raw).map_err(serde::de::Error::custom)) .transpose() } /// Serializes `None` as `null`. /// /// # Errors /// /// Only when the serializer fails. pub fn serialize( value: &Option, serializer: S, ) -> Result { match value { Some(timestamp) => serializer.collect_str(timestamp), None => serializer.serialize_none(), } } } /// `#[serde(with = "crate::time::epoch_seconds")]` for a Unix timestamp in /// whole seconds (the clone-code `expiry`). pub mod epoch_seconds { use jiff::Timestamp; use serde::{Deserialize, Deserializer, Serializer}; /// Deserializes an integer (or integral float) number of seconds. /// /// # Errors /// /// When the value is not a number or is out of range. pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { let seconds = serde_json::Number::deserialize(deserializer)?; let whole = seconds.as_i64().or_else(|| { seconds .as_f64() .filter(|f| f.fract() == 0.0 && f.abs() < 1e15) // The guard above keeps the value integral and in range. .map(|f| f as i64) }); let whole = whole.ok_or_else(|| { serde::de::Error::custom(format!("epoch seconds is not an integer: {seconds}")) })?; Timestamp::from_second(whole).map_err(serde::de::Error::custom) } /// Serializes as whole seconds. /// /// # Errors /// /// Only when the serializer fails. pub fn serialize(value: &Timestamp, serializer: S) -> Result { serializer.serialize_i64(value.as_second()) } } /// `#[serde(with = "crate::time::hms")]` for a required `H:MM:SS` duration. pub mod hms { use std::time::Duration; use serde::{Deserialize, Deserializer, Serializer}; /// Deserializes with [`super::parse_hms`]. /// /// # Errors /// /// When the value is not an `H:MM:SS` string. pub fn deserialize<'de, D: Deserializer<'de>>(deserializer: D) -> Result { let raw = String::deserialize(deserializer)?; super::parse_hms(&raw).map_err(serde::de::Error::custom) } /// Serializes with [`super::format_hms`]. /// /// # Errors /// /// Only when the serializer fails. pub fn serialize(value: &Duration, serializer: S) -> Result { serializer.serialize_str(&super::format_hms(*value)) } } /// `#[serde(default, with = "crate::time::option_hms")]` for an optional /// `H:MM:SS` duration. pub mod option_hms { use std::time::Duration; use serde::{Deserialize, Deserializer, Serializer}; /// Deserializes `null` as `None`, otherwise as [`super::hms`]. /// /// # Errors /// /// When the value is present but not `H:MM:SS`. pub fn deserialize<'de, D: Deserializer<'de>>( deserializer: D, ) -> Result, D::Error> { Option::::deserialize(deserializer)? .map(|raw| super::parse_hms(&raw).map_err(serde::de::Error::custom)) .transpose() } /// Serializes `None` as `null`. /// /// # Errors /// /// Only when the serializer fails. pub fn serialize( value: &Option, serializer: S, ) -> Result { match value { Some(duration) => serializer.serialize_str(&super::format_hms(*duration)), None => serializer.serialize_none(), } } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; fn ts(seconds: i64, nanos: i32) -> Timestamp { Timestamp::new(seconds, nanos).unwrap() } #[test] fn accepts_every_documented_spelling() { let table: &[(&str, Timestamp)] = &[ ("2023-03-31T00:00:00Z", ts(1_680_220_800, 0)), ("2023-03-01T00:00:00Z", ts(1_677_628_800, 0)), ( "2026-11-15T18:07:55.5931239Z", ts(1_794_766_075, 593_123_900), ), ("2026-11-15T18:07:55.5Z", ts(1_794_766_075, 500_000_000)), ( "2026-11-15T18:07:55.123456789Z", ts(1_794_766_075, 123_456_789), ), ("2007-05-29T04:00:00+00:00", ts(1_180_411_200, 0)), ("2007-05-29T00:00:00-04:00", ts(1_180_411_200, 0)), ("2007-05-29T09:30:00+0530", ts(1_180_411_200, 0)), ( "2007-05-29T04:00:00.25+00:00", ts(1_180_411_200, 250_000_000), ), ("05/29/2007", ts(1_180_396_800, 0)), ("5/9/2007", ts(1_178_668_800, 0)), ]; for (input, expected) in table { assert_eq!(parse_timestamp(input).unwrap(), *expected, "{input}"); } } #[test] fn rejects_everything_else_loudly() { for input in [ "", "2023-03-31", "2023-03-31T00:00:00", "2023-03-31 00:00:00Z", "2023-02-30T00:00:00Z", "2023-03-31T24:00:00Z", "2023-03-31T00:00:00.Z", "2023-03-31T00:00:00.1234567890Z", "2023-03-31T00:00:00Zjunk", "2023-03-31T00:00:00+25:00", "Jan 10 2023 7:00PM", "13/01/2023", "1/2/23", "1680220800", "now", ] { let error = parse_timestamp(input).unwrap_err(); assert_eq!(error.input, input); } } #[test] fn durations_parse_with_long_hours() { assert_eq!(parse_hms("21:02:06").unwrap(), Duration::from_secs(75_726)); assert_eq!(parse_hms("0:00:01").unwrap(), Duration::from_secs(1)); assert_eq!( parse_hms("104:00:00").unwrap(), Duration::from_secs(374_400) ); for bad in [ "", "21:02", "21:60:00", "21:02:6", "a:00:00", "1:00:00:00", "-1:00:00", ] { assert!(parse_hms(bad).is_err(), "{bad}"); } } #[test] fn durations_round_trip() { for raw in ["21:02:06", "0:00:01", "104:00:00"] { assert_eq!(format_hms(parse_hms(raw).unwrap()), raw); } } #[test] fn epoch_seconds_reads_integers_only() { #[derive(serde::Deserialize)] struct Wrapper { #[serde(with = "epoch_seconds")] at: Timestamp, } let parsed: Wrapper = serde_json::from_str(r#"{"at": 1700000000}"#).unwrap(); assert_eq!(parsed.at, ts(1_700_000_000, 0)); assert!(serde_json::from_str::(r#"{"at": 1.5}"#).is_err()); assert!(serde_json::from_str::(r#"{"at": "1700000000"}"#).is_err()); } }