//! UTC timestamps as TUF writes them, `YYYY-MM-DDTHH:MM:SSZ`, without a date crate. use std::time::{Duration, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; /// Days since 1970-01-01 → (year, month, day). Howard Hinnant's algorithm. fn civil(days: i64) -> (i64, u32, u32) { let z = days + 719_468; let era = z.div_euclid(146_097); let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let d = (doy - (153 * mp + 2) / 5 + 1) as u32; let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32; (yoe + era * 400 + i64::from(m <= 2), m, d) } /// (year, month, day) → days since 1970-01-01. fn days_from_civil(y: i64, m: u32, d: u32) -> i64 { let y = if m <= 2 { y - 1 } else { y }; let era = y.div_euclid(400); let yoe = y - era * 400; let mp = (i64::from(m) + 9) % 12; let doy = (153 * mp + 2) / 5 + i64::from(d) - 1; let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; era * 146_097 + doe - 719_468 } pub fn date(t: SystemTime) -> String { format(t)[..10].to_string() } pub fn format(t: SystemTime) -> String { let secs = t .duration_since(UNIX_EPOCH) .map(|d| d.as_secs()) .unwrap_or(0) as i64; let (y, m, d) = civil(secs.div_euclid(86_400)); let s = secs.rem_euclid(86_400); format!( "{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", s / 3600, s / 60 % 60, s % 60 ) } /// RFC 3339 in UTC: `2026-11-28T09:00:00Z`, fractional seconds allowed and ignored. pub fn parse(s: &str) -> Result { let bad = || format!("bad timestamp {s:?} (want YYYY-MM-DDTHH:MM:SSZ)"); let body = s.strip_suffix('Z').with_context(bad)?; let body = body.split('.').next().unwrap_or(body); let (date, clock) = body.split_once('T').with_context(bad)?; let n: Vec = date .split('-') .chain(clock.split(':')) .map(|p| p.parse::()) .collect::>() .ok() .with_context(bad)?; let [y, mo, d, h, mi, se] = n[..] else { bail!(bad()) }; if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 || y < 1970 { bail!(bad()); } let secs = days_from_civil(y, mo as u32, d as u32) * 86_400 + h * 3600 + mi * 60 + se; Ok(UNIX_EPOCH + Duration::from_secs(secs as u64)) } /// `90d`, `12h`, `30m`, `45s`. pub fn parse_duration(s: &str) -> Result { let (num, unit) = s.split_at(s.find(|c: char| !c.is_ascii_digit()).unwrap_or(s.len())); let n: u64 = num .parse() .with_context(|| format!("bad duration {s:?} (e.g. 90d, 12h)"))?; let mult = match unit { "d" => 86_400, "h" => 3600, "m" => 60, "s" | "" => 1, _ => bail!("bad duration {s:?} (e.g. 90d, 12h)"), }; Ok(Duration::from_secs(n * mult)) } #[cfg(test)] mod tests { use super::*; #[test] fn round_trips() { for s in [ "1970-01-01T00:00:00Z", "2024-02-29T23:59:59Z", "2026-11-28T09:30:05Z", "2100-03-01T12:00:00Z", ] { assert_eq!(format(parse(s).unwrap()), s); } assert_eq!( format(parse("2026-11-28T09:30:05.123Z").unwrap()), "2026-11-28T09:30:05Z" ); assert!(parse("2026-11-28 09:30:05").is_err()); assert!(parse("2026-13-01T00:00:00Z").is_err()); assert_eq!( date(UNIX_EPOCH + Duration::from_secs(20_000 * 86_400)), "2024-10-04" ); assert_eq!(parse_duration("90d").unwrap().as_secs(), 90 * 86_400); assert!(parse_duration("1y").is_err()); } }