fxprof_processed_profile/
reference_timestamp.rs

1use std::time::{Duration, SystemTime, UNIX_EPOCH};
2
3use serde::ser::{Serialize, Serializer};
4
5/// A timestamp which anchors the profile in absolute time.
6///
7/// In the profile JSON, this uses a UNIX timestamp.
8///
9/// All timestamps in the profile are relative to this reference timestamp.
10#[derive(Debug, Clone, Copy, PartialOrd, PartialEq)]
11pub struct ReferenceTimestamp {
12    ms_since_unix_epoch: f64,
13}
14
15impl ReferenceTimestamp {
16    /// Create a reference timestamp from a [`Duration`] since the UNIX epoch.
17    pub fn from_duration_since_unix_epoch(duration: Duration) -> Self {
18        Self::from_millis_since_unix_epoch(duration.as_secs_f64() * 1000.0)
19    }
20
21    /// Create a reference timestamp from milliseconds since the UNIX epoch.
22    pub fn from_millis_since_unix_epoch(ms_since_unix_epoch: f64) -> Self {
23        Self {
24            ms_since_unix_epoch,
25        }
26    }
27
28    /// Create a reference timestamp from a [`SystemTime`].
29    pub fn from_system_time(system_time: SystemTime) -> Self {
30        Self::from_duration_since_unix_epoch(system_time.duration_since(UNIX_EPOCH).unwrap())
31    }
32}
33
34impl From<SystemTime> for ReferenceTimestamp {
35    fn from(system_time: SystemTime) -> Self {
36        Self::from_system_time(system_time)
37    }
38}
39
40impl Serialize for ReferenceTimestamp {
41    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
42        self.ms_since_unix_epoch.serialize(serializer)
43    }
44}