Skip to content

Commit

Permalink
stats: Fix Instant deserialization (#599)
Browse files Browse the repository at this point in the history
  • Loading branch information
marcin-p-porebski authored Aug 7, 2024
1 parent 54b5843 commit 1b3e9c4
Showing 1 changed file with 9 additions and 14 deletions.
23 changes: 9 additions & 14 deletions webrtc/src/stats/serialize.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,31 +20,26 @@ pub mod instant_to_epoch_seconds {
.duration_since(UNIX_EPOCH)
.expect("Time went backwards");

let epoch_ms = epoch.as_millis() as f64 / 1000.0;
let epoch_s = epoch.as_millis() as f64 / 1000.0;

epoch_ms.serialize(serializer)
epoch_s.serialize(serializer)
}

pub fn deserialize<'de, D>(deserializer: D) -> Result<Instant, D::Error>
where
D: Deserializer<'de>,
{
let epoch_seconds: f64 = Deserialize::deserialize(deserializer)?;

let since_epoch = Duration::from_secs_f64(epoch_seconds);
let epoch_s = f64::deserialize(deserializer)?;
let epoch_duration = Duration::from_secs_f64(epoch_s);

let system_now = SystemTime::now();
let instant_now = Instant::now();

let deserialized_system_time = UNIX_EPOCH + since_epoch;

let adjustment = match deserialized_system_time.duration_since(system_now) {
Ok(duration) => -duration.as_secs_f64(),
Err(e) => e.duration().as_secs_f64(),
};

let adjusted_instant = instant_now + Duration::from_secs_f64(adjustment);
let duration_since_approx = system_now
.duration_since(UNIX_EPOCH + epoch_duration)
.expect("Time went backwards");
let instant = instant_now - duration_since_approx;

Ok(adjusted_instant)
Ok(instant)
}
}

0 comments on commit 1b3e9c4

Please sign in to comment.