Skip to main content

rtci_shared/
serde.rs

1/// Serializes a `SystemInstant` as epoch time in milliseconds, an `f64` with sub-millisecond
2/// precision: W3C stats timestamps are `DOMHighResTimeStamp`s, milliseconds that "SHOULD be
3/// accurate to 5 microseconds".
4pub mod instant_to_epoch {
5    use crate::time::SystemInstant;
6    use serde::{Deserialize, Deserializer, Serialize, Serializer};
7    use std::time::Duration;
8
9    /// Serializes an [`SystemInstant`] as a duration relative to the process's reference instant.
10    ///
11    /// [`SystemInstant`] has no absolute representation, so this encodes the offset instead. Use
12    /// with `#[serde(with = "...")]`.
13    ///
14    /// # Errors
15    ///
16    /// Propagates any failure from the underlying serializer.
17    pub fn serialize<S>(instant: &SystemInstant, serializer: S) -> Result<S::Ok, S::Error>
18    where
19        S: Serializer,
20    {
21        let epoch = instant.duration_since_unix_epoch();
22        let epoch_ms = epoch.as_secs_f64() * 1000.0;
23        epoch_ms.serialize(serializer)
24    }
25
26    /// Deserializes an [`SystemInstant`] from the relative offset written by [`serialize`].
27    ///
28    /// # Errors
29    ///
30    /// Propagates any failure from the underlying deserializer.
31    pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemInstant, D::Error>
32    where
33        D: Deserializer<'de>,
34    {
35        let epoch_ms = f64::deserialize(deserializer)?;
36        let epoch_duration = Duration::from_secs_f64(epoch_ms / 1000.0);
37        Ok(SystemInstant::from_epoch(epoch_duration))
38    }
39}
40
41#[cfg(test)]
42mod tests {
43    use super::instant_to_epoch;
44    use crate::time::SystemInstant;
45    use std::time::Duration;
46
47    // Milliseconds, with the sub-millisecond part kept (it was seconds truncated to whole
48    // milliseconds), and the same value read back.
49    #[test]
50    fn instant_to_epoch_is_milliseconds_with_sub_millisecond_precision() {
51        let at = SystemInstant::from_epoch(Duration::from_micros(1_794_904_159_643_250));
52        let json = instant_to_epoch::serialize(&at, serde_json::value::Serializer).unwrap();
53        let ms = json.as_f64().unwrap();
54        assert!((ms - 1_794_904_159_643.25).abs() < 0.001, "{ms}");
55        let back = instant_to_epoch::deserialize(json).unwrap();
56        let diff = back
57            .duration_since_unix_epoch()
58            .abs_diff(at.duration_since_unix_epoch());
59        assert!(diff < Duration::from_micros(1), "{diff:?}");
60    }
61}