rtc_shared/serde.rs
1/// Serializes a `SystemInstant` 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.
3pub mod instant_to_epoch {
4 use crate::time::SystemInstant;
5 use serde::{Deserialize, Deserializer, Serialize, Serializer};
6 use std::time::Duration;
7
8 /// Serializes an [`SystemInstant`] as a duration relative to the process's reference instant.
9 ///
10 /// [`SystemInstant`] has no absolute representation, so this encodes the offset instead. Use
11 /// with `#[serde(with = "...")]`.
12 ///
13 /// # Errors
14 ///
15 /// Propagates any failure from the underlying serializer.
16 pub fn serialize<S>(instant: &SystemInstant, serializer: S) -> Result<S::Ok, S::Error>
17 where
18 S: Serializer,
19 {
20 let epoch = instant.duration_since_unix_epoch();
21 let epoch_s = epoch.as_millis() as f64 / 1000.0;
22 epoch_s.serialize(serializer)
23 }
24
25 /// Deserializes an [`SystemInstant`] from the relative offset written by [`serialize`].
26 ///
27 /// # Errors
28 ///
29 /// Propagates any failure from the underlying deserializer.
30 pub fn deserialize<'de, D>(deserializer: D) -> Result<SystemInstant, D::Error>
31 where
32 D: Deserializer<'de>,
33 {
34 let epoch_s = f64::deserialize(deserializer)?;
35 let epoch_duration = Duration::from_secs_f64(epoch_s);
36 Ok(SystemInstant::from_epoch(epoch_duration))
37 }
38}