jacquardSnapshot

← snapshot

2679 bytes
//! A minimal RFC3339 formatter from epoch milliseconds.
//!
//! Kept hand-rolled rather than pulling in `chrono`: the workspace's stated
//! posture is a deliberately small external dependency graph, and this is a
//! days-from-civil calculation any calendar reference documents identically
//! (Howard Hinnant's `civil_from_days`).

/// Formats `at_ms` (milliseconds since the Unix epoch, UTC) as
/// `YYYY-MM-DDTHH:MM:SS.mmmZ`.
pub(crate) fn format_rfc3339_ms(at_ms: i64) -> String {
    let days = at_ms.div_euclid(86_400_000);
    let ms_of_day = at_ms.rem_euclid(86_400_000);

    let (year, month, day) = civil_from_days(days);
    let hour = ms_of_day / 3_600_000;
    let minute = (ms_of_day / 60_000) % 60;
    let second = (ms_of_day / 1_000) % 60;
    let millis = ms_of_day % 1_000;

    format!("{year:04}-{month:02}-{day:02}T{hour:02}:{minute:02}:{second:02}.{millis:03}Z")
}

/// Days-since-epoch to `(year, month, day)`, proleptic Gregorian.
fn civil_from_days(z: i64) -> (i64, u32, u32) {
    let z = z + 719_468;
    let era = z.div_euclid(146_097);
    let doe = z.rem_euclid(146_097); // [0, 146096]
    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365; // [0, 399]
    let y = yoe + era * 400;
    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); // [0, 365]
    let mp = (5 * doy + 2) / 153; // [0, 11]
    let d = doy - (153 * mp + 2) / 5 + 1; // [1, 31]
    let m = if mp < 10 { mp + 3 } else { mp - 9 }; // [1, 12]
    let y = if m <= 2 { y + 1 } else { y };
    (
        y,
        u32::try_from(m).unwrap_or(1),
        u32::try_from(d).unwrap_or(1),
    )
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn epoch_formats_as_the_epoch() {
        assert_eq!(format_rfc3339_ms(0), "1970-01-01T00:00:00.000Z");
    }

    #[test]
    fn a_known_instant_matches() {
        // 2025-05-11T21:46:40.000Z, cross-checked against `date -u`.
        assert_eq!(
            format_rfc3339_ms(1_747_000_000_000),
            "2025-05-11T21:46:40.000Z"
        );
    }

    #[test]
    fn millis_are_preserved() {
        assert_eq!(
            format_rfc3339_ms(1_747_000_000_123),
            "2025-05-11T21:46:40.123Z"
        );
    }

    #[test]
    fn pre_epoch_instants_round_trip_the_right_direction() {
        // One second before the epoch: 1969-12-31T23:59:59.000Z, not a
        // negative-day wraparound artifact.
        assert_eq!(format_rfc3339_ms(-1_000), "1969-12-31T23:59:59.000Z");
    }

    #[test]
    fn leap_day_lands_on_february_29() {
        // 2024-02-29T00:00:00Z
        assert_eq!(
            format_rfc3339_ms(1_709_164_800_000),
            "2024-02-29T00:00:00.000Z"
        );
    }
}