fxprof_processed_profile/
timestamp.rs

1use serde::ser::{Serialize, Serializer};
2
3/// The type used for sample and marker timestamps.
4///
5/// Timestamps in the profile are stored in reference to the profile's [`ReferenceTimestamp`](crate::ReferenceTimestamp).
6#[derive(Debug, Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
7pub struct Timestamp {
8    nanos: u64,
9}
10
11impl Timestamp {
12    pub fn from_nanos_since_reference(nanos: u64) -> Self {
13        Self { nanos }
14    }
15
16    pub fn from_millis_since_reference(millis: f64) -> Self {
17        Self {
18            nanos: (millis * 1_000_000.0) as u64,
19        }
20    }
21}
22
23impl Serialize for Timestamp {
24    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
25        // In the profile JSON, timestamps are currently expressed as float milliseconds
26        // since profile.meta.startTime.
27        serializer.serialize_f64((self.nanos as f64) / 1_000_000.0)
28    }
29}
30
31pub struct SerializableTimestampSliceAsDeltas<'a>(pub &'a [Timestamp]);
32
33impl Serialize for SerializableTimestampSliceAsDeltas<'_> {
34    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
35    where
36        S: Serializer,
37    {
38        let mut prev_nanos = 0;
39        let delta_millis_iter = self.0.iter().map(|ts| {
40            let cur_nanos = ts.nanos;
41            let delta_nanos = cur_nanos - prev_nanos;
42            prev_nanos = cur_nanos;
43            (delta_nanos as f64) / 1_000_000.0
44        });
45        serializer.collect_seq(delta_millis_iter)
46    }
47}
48
49pub struct SerializableTimestampSliceAsDeltasWithPermutation<'a>(
50    pub &'a [Timestamp],
51    pub &'a [usize],
52);
53
54impl Serialize for SerializableTimestampSliceAsDeltasWithPermutation<'_> {
55    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
56    where
57        S: Serializer,
58    {
59        let mut prev_nanos = 0;
60        let delta_millis_iter = self.1.iter().map(|i| {
61            let cur_nanos = self.0[*i].nanos;
62            let delta_nanos = cur_nanos - prev_nanos;
63            prev_nanos = cur_nanos;
64            (delta_nanos as f64) / 1_000_000.0
65        });
66        serializer.collect_seq(delta_millis_iter)
67    }
68}