fxprof_processed_profile/
reference_timestamp.rs

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