rtc_shared/
serde.rs

1/// Serializes a `tokio::time::Instant` to an approximation of epoch time in the form
2/// of an `f64` where the integer portion is seconds and the decimal portion is milliseconds.
3/// For instance, `Monday, May 30, 2022 10:45:26.456 PM UTC` converts to `1653950726.456`.
4///
5/// Note that an `Instant` is not connected to real world time, so this conversion is
6/// approximate.
7pub mod instant_to_epoch {
8    use serde::{Deserialize, Deserializer, Serialize, Serializer};
9    use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
10
11    pub fn serialize<S>(instant: &Instant, serializer: S) -> Result<S::Ok, S::Error>
12    where
13        S: Serializer,
14    {
15        let system_now = SystemTime::now();
16        let instant_now = Instant::now();
17        let approx = system_now - (instant_now - *instant);
18        let epoch = approx
19            .duration_since(UNIX_EPOCH)
20            .expect("Time went backwards");
21
22        let epoch_s = epoch.as_millis() as f64 / 1000.0;
23
24        epoch_s.serialize(serializer)
25    }
26
27    pub fn deserialize<'de, D>(deserializer: D) -> Result<Instant, D::Error>
28    where
29        D: Deserializer<'de>,
30    {
31        let epoch_s = f64::deserialize(deserializer)?;
32        let epoch_duration = Duration::from_secs_f64(epoch_s);
33
34        let system_now = SystemTime::now();
35        let instant_now = Instant::now();
36
37        let duration_since_approx = system_now
38            .duration_since(UNIX_EPOCH + epoch_duration)
39            .expect("Time went backwards");
40        let instant = instant_now - duration_since_approx;
41
42        Ok(instant)
43    }
44}