Skip to content

Commit

Permalink
Remove some TimeTravel error cases (#1636)
Browse files Browse the repository at this point in the history
* Remove some TimeTravel error cases

This might make our code more robust.

* Remove invalid test

---------

Co-authored-by: Lars Eggert <[email protected]>
  • Loading branch information
martinthomson and larseggert authored Feb 9, 2024
1 parent 5c0afc9 commit 2201a7f
Showing 1 changed file with 35 additions and 18 deletions.
53 changes: 35 additions & 18 deletions neqo-crypto/src/time.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,29 +106,39 @@ impl TryFrom<PRTime> for Time {
type Error = Error;
fn try_from(prtime: PRTime) -> Res<Self> {
let base = get_base();
if let Some(delta) = prtime.checked_sub(base.prtime) {
let d = Duration::from_micros(delta.try_into()?);
base.instant
.checked_add(d)
.map_or(Err(Error::TimeTravelError), |t| Ok(Self { t }))
let delta = prtime
.checked_sub(base.prtime)
.ok_or(Error::TimeTravelError)?;
let d = Duration::from_micros(u64::try_from(delta.abs())?);
let t = if delta >= 0 {
base.instant.checked_add(d)
} else {
Err(Error::TimeTravelError)
}
base.instant.checked_sub(d)
};
let t = t.ok_or(Error::TimeTravelError)?;
Ok(Self { t })
}
}

impl TryInto<PRTime> for Time {
type Error = Error;
fn try_into(self) -> Res<PRTime> {
let base = get_base();
let delta = self
.t
.checked_duration_since(base.instant)
.ok_or(Error::TimeTravelError)?;
if let Ok(d) = PRTime::try_from(delta.as_micros()) {
d.checked_add(base.prtime).ok_or(Error::TimeTravelError)

if let Some(delta) = self.t.checked_duration_since(base.instant) {
if let Ok(d) = PRTime::try_from(delta.as_micros()) {
d.checked_add(base.prtime).ok_or(Error::TimeTravelError)
} else {
Err(Error::TimeTravelError)
}
} else {
Err(Error::TimeTravelError)
// Try to go backwards from the base time.
let backwards = base.instant - self.t; // infallible
if let Ok(d) = PRTime::try_from(backwards.as_micros()) {
base.prtime.checked_sub(d).ok_or(Error::TimeTravelError)
} else {
Err(Error::TimeTravelError)
}
}
}
}
Expand Down Expand Up @@ -226,16 +236,23 @@ mod test {
}

#[test]
fn past_time() {
fn past_prtime() {
const DELTA: Duration = Duration::from_secs(1);
init();
let base = get_base();
assert!(Time::try_from(base.prtime - 1).is_err());
let delta_micros = PRTime::try_from(DELTA.as_micros()).unwrap();
println!("{} - {}", base.prtime, delta_micros);
let t = Time::try_from(base.prtime - delta_micros).unwrap();
assert_eq!(Instant::from(t) + DELTA, base.instant);
}

#[test]
fn negative_time() {
fn past_instant() {
const DELTA: Duration = Duration::from_secs(1);
init();
assert!(Time::try_from(-1).is_err());
let base = get_base();
let t = Time::from(base.instant.checked_sub(DELTA).unwrap());
assert_eq!(Instant::from(t) + DELTA, base.instant);
}

#[test]
Expand Down

0 comments on commit 2201a7f

Please sign in to comment.