Skip to main content

yapi_types/
time.rs

1//! Timestamps as pi writes them: Unix milliseconds and ISO 8601 UTC with
2//! milliseconds, and ids.
3
4use std::time::{SystemTime, UNIX_EPOCH};
5
6/// Unix time in milliseconds.
7pub fn now_ms() -> u64 {
8    SystemTime::now()
9        .duration_since(UNIX_EPOCH)
10        .map_or(0, |elapsed| elapsed.as_millis() as u64)
11}
12
13/// `2026-10-02T14:49:48.573Z`, as JavaScript's `Date.toISOString`.
14pub fn iso(ms: u64) -> String {
15    let days = (ms / 86_400_000) as i64;
16    let rest = ms % 86_400_000;
17    let (year, month, day) = civil_from_days(days);
18    format!(
19        "{year:04}-{month:02}-{day:02}T{:02}:{:02}:{:02}.{:03}Z",
20        rest / 3_600_000,
21        rest / 60_000 % 60,
22        rest / 1000 % 60,
23        rest % 1000
24    )
25}
26
27/// The current time as [`iso`].
28pub fn now_iso() -> String {
29    iso(now_ms())
30}
31
32/// Parses [`iso`] output, and offsets other than `Z`, to Unix milliseconds.
33pub fn parse_iso(text: &str) -> Option<u64> {
34    let bytes = text.as_bytes();
35    if bytes.len() < 19 || bytes[4] != b'-' || bytes[7] != b'-' || bytes[13] != b':' {
36        return None;
37    }
38    let number = |range: std::ops::Range<usize>| text.get(range)?.parse::<i64>().ok();
39    let (year, month, day) = (number(0..4)?, number(5..7)?, number(8..10)?);
40    let (hour, minute, second) = (number(11..13)?, number(14..16)?, number(17..19)?);
41    let mut rest = &text[19..];
42    let mut millis = 0;
43    if let Some(fraction) = rest.strip_prefix('.') {
44        let digits: String = fraction.chars().take_while(char::is_ascii_digit).collect();
45        rest = &fraction[digits.len()..];
46        millis = format!("{digits:0<3}")[..3].parse::<i64>().ok()?;
47    }
48    let offset_minutes = match rest {
49        "Z" | "" => 0,
50        offset => {
51            let sign = if offset.starts_with('-') { -1 } else { 1 };
52            let hours = offset.get(1..3)?.parse::<i64>().ok()?;
53            let minutes = offset
54                .get(4..6)
55                .and_then(|m| m.parse::<i64>().ok())
56                .unwrap_or(0);
57            sign * (hours * 60 + minutes)
58        }
59    };
60    let days = days_from_civil(year, month, day);
61    let ms = ((days * 24 + hour) * 60 + minute - offset_minutes) * 60_000 + second * 1000 + millis;
62    u64::try_from(ms).ok()
63}
64
65/// Howard Hinnant's algorithm: days since 1970-01-01 to (year, month, day).
66fn civil_from_days(days: i64) -> (i64, u32, u32) {
67    let z = days + 719_468;
68    let era = z.div_euclid(146_097);
69    let doe = z.rem_euclid(146_097);
70    let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
71    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
72    let mp = (5 * doy + 2) / 153;
73    let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
74    let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
75    let year = yoe + era * 400 + i64::from(month <= 2);
76    (year, month, day)
77}
78
79fn days_from_civil(year: i64, month: i64, day: i64) -> i64 {
80    let year = if month <= 2 { year - 1 } else { year };
81    let era = year.div_euclid(400);
82    let yoe = year.rem_euclid(400);
83    let mp = if month > 2 { month - 3 } else { month + 9 };
84    let doy = (153 * mp + 2) / 5 + day - 1;
85    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
86    era * 146_097 + doe - 719_468
87}
88
89/// `N` bytes from the OS generator; zeros on a platform without one.
90pub fn random_bytes<const N: usize>() -> [u8; N] {
91    let mut bytes = [0u8; N];
92    let _ = getrandom::fill(&mut bytes);
93    bytes
94}
95
96/// `bytes` as lowercase hexadecimal.
97pub fn hex(bytes: &[u8]) -> String {
98    bytes.iter().map(|byte| format!("{byte:02x}")).collect()
99}
100
101/// `count` random bytes as lowercase hexadecimal.
102pub fn random_hex(count: usize) -> String {
103    let mut bytes = vec![0u8; count];
104    let _ = getrandom::fill(&mut bytes);
105    hex(&bytes)
106}
107
108/// A random UUID v4, as `crypto.randomUUID`.
109pub fn uuid_v4() -> String {
110    let mut bytes = random_bytes::<16>();
111    bytes[6] = (bytes[6] & 0x0f) | 0x40;
112    bytes[8] = (bytes[8] & 0x3f) | 0x80;
113    format_uuid(&bytes)
114}
115
116/// A time-ordered UUID v7, used for session ids.
117pub fn uuid_v7() -> String {
118    let mut bytes = random_bytes::<16>();
119    bytes[..6].copy_from_slice(&now_ms().to_be_bytes()[2..]);
120    bytes[6] = (bytes[6] & 0x0f) | 0x70;
121    bytes[8] = (bytes[8] & 0x3f) | 0x80;
122    format_uuid(&bytes)
123}
124
125fn format_uuid(bytes: &[u8; 16]) -> String {
126    format!(
127        "{}-{}-{}-{}-{}",
128        hex(&bytes[..4]),
129        hex(&bytes[4..6]),
130        hex(&bytes[6..8]),
131        hex(&bytes[8..10]),
132        hex(&bytes[10..])
133    )
134}
135
136#[cfg(test)]
137mod tests {
138    use super::*;
139
140    #[test]
141    fn round_trips_iso() {
142        let ms = 1_790_952_595_641;
143        assert_eq!(iso(ms), "2026-10-02T14:49:55.641Z");
144        assert_eq!(parse_iso("2026-10-02T14:49:55.641Z"), Some(ms));
145        assert_eq!(parse_iso("2026-10-02T16:49:55.641+02:00"), Some(ms));
146        assert_eq!(iso(0), "1970-01-01T00:00:00.000Z");
147        assert_eq!(parse_iso("2024-02-29T00:00:00Z"), Some(1_709_164_800_000));
148    }
149
150    #[test]
151    fn makes_uuids() {
152        let v7 = uuid_v7();
153        assert_eq!(v7.len(), 36);
154        assert_eq!(&v7[14..15], "7");
155        assert_eq!(&uuid_v4()[14..15], "4");
156    }
157}