1use std::time::{SystemTime, UNIX_EPOCH};
5
6pub fn now_ms() -> u64 {
8 SystemTime::now()
9 .duration_since(UNIX_EPOCH)
10 .map_or(0, |elapsed| elapsed.as_millis() as u64)
11}
12
13pub 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
27pub fn now_iso() -> String {
29 iso(now_ms())
30}
31
32pub 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
65fn 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
89pub fn try_random_bytes<const N: usize>() -> std::io::Result<[u8; N]> {
91 let mut bytes = [0u8; N];
92 fill(&mut bytes)?;
93 Ok(bytes)
94}
95
96pub fn random_bytes<const N: usize>() -> [u8; N] {
99 let mut bytes = [0u8; N];
100 fill_or_panic(&mut bytes);
101 bytes
102}
103
104fn fill(bytes: &mut [u8]) -> std::io::Result<()> {
105 #[cfg(test)]
106 if tests::NO_RANDOM.get() {
107 return Err(std::io::Error::other("unavailable"));
108 }
109 getrandom::fill(bytes).map_err(std::io::Error::other)
110}
111
112fn fill_or_panic(bytes: &mut [u8]) {
113 if let Err(err) = fill(bytes) {
115 panic!("The OS random generator failed: {err}");
116 }
117}
118
119pub fn hex(bytes: &[u8]) -> String {
121 bytes.iter().map(|byte| format!("{byte:02x}")).collect()
122}
123
124pub fn random_hex(count: usize) -> String {
127 let mut bytes = vec![0u8; count];
128 fill_or_panic(&mut bytes);
129 hex(&bytes)
130}
131
132pub fn uuid_v4() -> String {
134 v4(random_bytes())
135}
136
137pub fn try_uuid_v4() -> std::io::Result<String> {
139 try_random_bytes().map(v4)
140}
141
142fn v4(mut bytes: [u8; 16]) -> String {
143 bytes[6] = (bytes[6] & 0x0f) | 0x40;
144 bytes[8] = (bytes[8] & 0x3f) | 0x80;
145 format_uuid(&bytes)
146}
147
148pub fn uuid_v7() -> String {
151 let mut bytes = random_bytes::<16>();
152 bytes[..6].copy_from_slice(&now_ms().to_be_bytes()[2..]);
153 bytes[6] = (bytes[6] & 0x0f) | 0x70;
154 bytes[8] = (bytes[8] & 0x3f) | 0x80;
155 format_uuid(&bytes)
156}
157
158fn format_uuid(bytes: &[u8; 16]) -> String {
159 format!(
160 "{}-{}-{}-{}-{}",
161 hex(&bytes[..4]),
162 hex(&bytes[4..6]),
163 hex(&bytes[6..8]),
164 hex(&bytes[8..10]),
165 hex(&bytes[10..])
166 )
167}
168
169#[cfg(test)]
170mod tests {
171 use std::cell::Cell;
172
173 use super::*;
174
175 thread_local! {
176 pub(super) static NO_RANDOM: Cell<bool> = const { Cell::new(false) };
178 }
179
180 #[test]
181 fn round_trips_iso() {
182 let ms = 1_790_952_595_641;
183 assert_eq!(iso(ms), "2026-10-02T14:49:55.641Z");
184 assert_eq!(parse_iso("2026-10-02T14:49:55.641Z"), Some(ms));
185 assert_eq!(parse_iso("2026-10-02T16:49:55.641+02:00"), Some(ms));
186 assert_eq!(iso(0), "1970-01-01T00:00:00.000Z");
187 assert_eq!(parse_iso("2024-02-29T00:00:00Z"), Some(1_709_164_800_000));
188 }
189
190 #[test]
191 fn makes_uuids() {
192 let v7 = uuid_v7();
193 assert_eq!(v7.len(), 36);
194 assert_eq!(&v7[14..15], "7");
195 assert_eq!(&uuid_v4()[14..15], "4");
196 assert_eq!(&try_uuid_v4().unwrap()[14..15], "4");
197 assert_ne!(random_hex(8), random_hex(8));
198 NO_RANDOM.set(true);
200 assert!(try_random_bytes::<16>().is_err());
201 assert!(try_uuid_v4().is_err());
202 assert!(std::panic::catch_unwind(uuid_v4).is_err());
203 assert!(std::panic::catch_unwind(|| random_hex(8)).is_err());
204 NO_RANDOM.set(false);
205 }
206}