spoolframe_types/
serde_time.rs1use std::time::{Duration, SystemTime, UNIX_EPOCH};
19
20use serde::{Deserialize, Deserializer, Serialize, Serializer};
21
22fn from_epoch(at: SystemTime, unit: fn(Duration) -> u128) -> i64 {
25 match at.duration_since(UNIX_EPOCH) {
26 Ok(after) => i64::try_from(unit(after)).unwrap_or(i64::MAX),
27 Err(before) => i64::try_from(unit(before.duration())).map_or(i64::MIN, |n| -n),
28 }
29}
30
31fn at_epoch(n: i64, unit: fn(u64) -> Duration) -> Option<SystemTime> {
34 let span = unit(n.unsigned_abs());
35 if n < 0 {
36 UNIX_EPOCH.checked_sub(span)
37 } else {
38 UNIX_EPOCH.checked_add(span)
39 }
40}
41
42pub fn epoch() -> SystemTime {
45 UNIX_EPOCH
46}
47
48fn held<T, E: serde::de::Error>(value: Option<T>, n: impl std::fmt::Display) -> Result<T, E> {
51 value.ok_or_else(|| E::custom(format_args!("time {n} is out of range here")))
52}
53
54macro_rules! serde_with {
57 ($ty:ty, $wire:ty) => {
58 pub fn serialize<S: Serializer>(value: &$ty, s: S) -> Result<S::Ok, S::Error> {
59 to_wire(*value).serialize(s)
60 }
61
62 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<$ty, D::Error> {
63 let n = <$wire>::deserialize(d)?;
64 held(try_from_wire(n), n)
65 }
66
67 pub mod option {
70 use super::*;
71
72 pub fn serialize<S: Serializer>(value: &Option<$ty>, s: S) -> Result<S::Ok, S::Error> {
73 value.map(to_wire).serialize(s)
74 }
75
76 pub fn deserialize<'de, D: Deserializer<'de>>(d: D) -> Result<Option<$ty>, D::Error> {
77 Option::<$wire>::deserialize(d)?
78 .map(|n| held(try_from_wire(n), n))
79 .transpose()
80 }
81 }
82
83 pub mod option_required {
85 pub use super::option::{deserialize, serialize};
86 }
87 };
88}
89
90macro_rules! unix_time {
92 ($(#[$doc:meta])* $name:ident, $as_units:expr, $from_units:path) => {
93 $(#[$doc])*
94 pub mod $name {
95 use super::*;
96
97 pub fn to_wire(at: SystemTime) -> i64 {
98 from_epoch(at, $as_units)
99 }
100
101 pub fn try_from_wire(n: i64) -> Option<SystemTime> {
103 at_epoch(n, $from_units)
104 }
105
106 pub fn from_wire(n: i64) -> SystemTime {
110 try_from_wire(n).unwrap_or(UNIX_EPOCH)
111 }
112
113 pub fn now() -> SystemTime {
115 from_wire(to_wire(SystemTime::now()))
116 }
117
118 serde_with!(SystemTime, i64);
119 }
120 };
121}
122
123unix_time!(
124 unix_seconds,
126 |d| u128::from(d.as_secs()),
127 Duration::from_secs
128);
129
130unix_time!(
131 unix_millis,
133 |d| d.as_millis(),
134 Duration::from_millis
135);
136
137pub mod millis {
139 use super::*;
140
141 pub fn to_wire(span: Duration) -> u64 {
142 u64::try_from(span.as_millis()).unwrap_or(u64::MAX)
143 }
144
145 pub fn from_wire(millis: u64) -> Duration {
146 Duration::from_millis(millis)
147 }
148
149 fn try_from_wire(millis: u64) -> Option<Duration> {
151 Some(from_wire(millis))
152 }
153
154 pub fn whole(span: Duration) -> Duration {
156 from_wire(to_wire(span))
157 }
158
159 serde_with!(Duration, u64);
160}
161
162#[cfg(test)]
163mod tests {
164 use serde::{Deserialize, Serialize};
165 use serde_json::json;
166
167 use super::*;
168
169 #[derive(Debug, PartialEq, Serialize, Deserialize)]
170 struct Times {
171 #[serde(rename = "at", with = "unix_seconds")]
172 seconds: SystemTime,
173 #[serde(with = "unix_seconds::option_required")]
174 seconds_none: Option<SystemTime>,
175 #[serde(with = "unix_millis")]
176 millis_at: SystemTime,
177 #[serde(default, with = "unix_millis::option")]
178 millis_at_some: Option<SystemTime>,
179 #[serde(with = "millis")]
180 span: Duration,
181 #[serde(default, with = "millis::option")]
182 span_some: Option<Duration>,
183 }
184
185 fn times() -> Times {
186 Times {
187 seconds: UNIX_EPOCH + Duration::from_secs(1_761_700_000),
188 seconds_none: None,
189 millis_at: UNIX_EPOCH + Duration::from_millis(1_761_700_000_123),
190 millis_at_some: Some(UNIX_EPOCH - Duration::from_millis(1_500)),
191 span: Duration::from_millis(258_865),
192 span_some: Some(Duration::from_millis(7)),
193 }
194 }
195
196 #[test]
198 fn each_helper_writes_one_integer_and_reads_it_back() {
199 let wire = json!({
200 "at": 1_761_700_000,
201 "seconds_none": null,
202 "millis_at": 1_761_700_000_123_i64,
203 "millis_at_some": -1_500,
204 "span": 258_865,
205 "span_some": 7,
206 });
207 assert_eq!(serde_json::to_value(times()).unwrap(), wire);
208 assert_eq!(serde_json::from_value::<Times>(wire).unwrap(), times());
209 }
210
211 #[test]
213 fn a_time_before_the_epoch_is_negative() {
214 let at = UNIX_EPOCH - Duration::from_secs(90);
215 assert_eq!(unix_seconds::to_wire(at), -90);
216 assert_eq!(unix_seconds::from_wire(-90), at);
217 let between = UNIX_EPOCH - Duration::from_millis(1_500);
218 assert_eq!(unix_seconds::to_wire(between), -1);
219 }
220
221 #[test]
226 fn a_time_out_of_range_is_refused_not_a_panic() {
227 for n in [i64::MIN, -1, i64::MAX] {
228 let mut wire = serde_json::to_value(times()).unwrap();
229 wire["at"] = json!(n);
230 wire["seconds_none"] = json!(n);
231 wire["millis_at"] = json!(n);
232 serde_json::from_value::<Times>(wire).unwrap();
233 }
234 let refused = held::<SystemTime, serde_json::Error>(None, -1).unwrap_err();
235 assert_eq!(refused.to_string(), "time -1 is out of range here");
236 }
237
238 #[test]
241 fn an_option_left_out_is_refused() {
242 let mut wire = serde_json::to_value(times()).unwrap();
243 wire.as_object_mut().unwrap().remove("seconds_none");
244 let error = serde_json::from_value::<Times>(wire).unwrap_err();
245 assert!(error.to_string().contains("missing field"), "{error}");
246 }
247
248 #[test]
251 fn whole_units_read_back_equal() {
252 let now = unix_seconds::now();
253 assert_eq!(unix_seconds::from_wire(unix_seconds::to_wire(now)), now);
254 let span = Duration::from_micros(61_234_567);
255 assert_eq!(millis::whole(span), Duration::from_millis(61_234));
256 }
257
258 #[test]
262 fn every_optional_time_field_has_a_default() {
263 let crates = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("..");
264 let mut missing = Vec::new();
265 let mut stack = vec![crates];
266 while let Some(dir) = stack.pop() {
267 for entry in std::fs::read_dir(&dir).unwrap().flatten() {
268 let path = entry.path();
269 let name = entry.file_name();
270 if path.is_dir() && name != "target" && name != "node_modules" {
271 stack.push(path);
272 } else if path.extension().is_some_and(|e| e == "rs") {
273 let text = std::fs::read_to_string(&path).unwrap();
274 let lines: Vec<&str> = text.lines().collect();
275 for (n, line) in lines.iter().enumerate() {
276 let optional = ["seconds::option\"", "millis::option\""]
277 .iter()
278 .any(|m| line.contains(m));
279 let from = (0..=n)
281 .rev()
282 .take(5)
283 .find(|&i| lines[i].contains("#[serde("));
284 let defaulted = from.is_some_and(|from| {
285 lines[from..=n].iter().any(|l| l.contains("default"))
286 });
287 if optional && from.is_some() && !defaulted {
288 missing.push(format!("{}:{}", path.display(), n + 1));
289 }
290 }
291 }
292 }
293 }
294 assert!(
295 missing.is_empty(),
296 "`option` without `default`: {missing:?}"
297 );
298 }
299}