Skip to main content

ic_host_text/timestamp/
mod.rs

1//! Canonical UTC second timestamps without clocks, timezones or freshness policy.
2
3#[cfg(test)]
4mod tests;
5
6/// Parse the exact UTC spelling emitted by [`format_utc_timestamp_secs`].
7///
8/// Accepts Unix seconds from zero through `i64::MAX`; larger dates refuse.
9/// Fractional seconds, offsets, nonminimal fields and impossible dates refuse.
10#[must_use]
11pub fn parse_utc_timestamp_secs(value: &str) -> Option<u64> {
12    let original = value;
13    let value = value.strip_suffix('Z')?;
14    let (date, time) = value.split_once('T')?;
15    let mut date_parts = date.split('-');
16    let year = date_parts.next()?.parse::<i64>().ok()?;
17    let month = date_parts.next()?.parse::<u32>().ok()?;
18    let day = date_parts.next()?.parse::<u32>().ok()?;
19    if date_parts.next().is_some() {
20        return None;
21    }
22    let mut time_parts = time.split(':');
23    let hour = time_parts.next()?.parse::<u32>().ok()?;
24    let minute = time_parts.next()?.parse::<u32>().ok()?;
25    let second = time_parts.next()?.parse::<u32>().ok()?;
26    if time_parts.next().is_some()
27        || !(1..=12).contains(&month)
28        || !(1..=31).contains(&day)
29        || hour > 23
30        || minute > 59
31        || second > 59
32    {
33        return None;
34    }
35    let days = days_from_civil(year, month, day)?;
36    let seconds = days
37        .checked_mul(86_400)?
38        .checked_add(i64::from(hour) * 3_600)?
39        .checked_add(i64::from(minute) * 60)?
40        .checked_add(i64::from(second))?;
41    let seconds = u64::try_from(seconds).ok()?;
42    (format_utc_timestamp_secs(seconds) == original).then_some(seconds)
43}
44
45/// Format unsigned Unix seconds as canonical UTC text with second precision.
46///
47/// Years use at least four digits with no leading sign. Values through `u64::MAX`
48/// format without a clock or timezone; parsing intentionally stops at `i64::MAX`.
49#[must_use]
50pub fn format_utc_timestamp_secs(value: u64) -> String {
51    let days = i64::try_from(value / 86_400).unwrap_or(i64::MAX);
52    let seconds_of_day = value % 86_400;
53    let (year, month, day) = civil_from_days(days);
54    let hour = seconds_of_day / 3_600;
55    let minute = (seconds_of_day % 3_600) / 60;
56    let second = seconds_of_day % 60;
57    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}Z")
58}
59
60fn civil_from_days(days: i64) -> (i64, i64, i64) {
61    let days = days + 719_468;
62    let era = if days >= 0 { days } else { days - 146_096 } / 146_097;
63    let day_of_era = days - era * 146_097;
64    let year_of_era =
65        (day_of_era - day_of_era / 1_460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
66    let mut year = year_of_era + era * 400;
67    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
68    let month_prime = (5 * day_of_year + 2) / 153;
69    let day = day_of_year - (153 * month_prime + 2) / 5 + 1;
70    let month = month_prime + if month_prime < 10 { 3 } else { -9 };
71    year += i64::from(month <= 2);
72    (year, month, day)
73}
74
75fn days_from_civil(year: i64, month: u32, day: u32) -> Option<i64> {
76    let month = i64::from(month);
77    let day = i64::from(day);
78    let year = year.checked_sub(i64::from(month <= 2))?;
79    let era = if year >= 0 {
80        year
81    } else {
82        year.checked_sub(399)?
83    } / 400;
84    let year_of_era = year - era * 400;
85    let month_prime = month + if month > 2 { -3 } else { 9 };
86    let day_of_year = (153 * month_prime + 2) / 5 + day - 1;
87    let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year;
88    era.checked_mul(146_097)?
89        .checked_add(day_of_era)?
90        .checked_sub(719_468)
91}