824: embassy/time: round up by default in duration conversions. Fixes #823 r=Dirbaio a=Dirbaio



Co-authored-by: Dario Nieuwenhuis <dirbaio@dirbaio.net>
This commit is contained in:
bors[bot] 2022-06-24 21:29:29 +00:00 committed by GitHub
commit a51df0dec6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -41,23 +41,45 @@ impl Duration {
Duration { ticks } Duration { ticks }
} }
/// Creates a duration from the specified number of seconds /// Creates a duration from the specified number of seconds, rounding up.
pub const fn from_secs(secs: u64) -> Duration { pub const fn from_secs(secs: u64) -> Duration {
Duration { Duration {
ticks: secs * TICKS_PER_SECOND, ticks: secs * TICKS_PER_SECOND,
} }
} }
/// Creates a duration from the specified number of milliseconds /// Creates a duration from the specified number of milliseconds, rounding up.
pub const fn from_millis(millis: u64) -> Duration { pub const fn from_millis(millis: u64) -> Duration {
Duration {
ticks: div_ceil(millis * (TICKS_PER_SECOND / GCD_1K), 1000 / GCD_1K),
}
}
/// Creates a duration from the specified number of microseconds, rounding up.
/// NOTE: Delays this small may be inaccurate.
pub const fn from_micros(micros: u64) -> Duration {
Duration {
ticks: div_ceil(micros * (TICKS_PER_SECOND / GCD_1M), 1_000_000 / GCD_1M),
}
}
/// Creates a duration from the specified number of seconds, rounding down.
pub const fn from_secs_floor(secs: u64) -> Duration {
Duration {
ticks: secs * TICKS_PER_SECOND,
}
}
/// Creates a duration from the specified number of milliseconds, rounding down.
pub const fn from_millis_floor(millis: u64) -> Duration {
Duration { Duration {
ticks: millis * (TICKS_PER_SECOND / GCD_1K) / (1000 / GCD_1K), ticks: millis * (TICKS_PER_SECOND / GCD_1K) / (1000 / GCD_1K),
} }
} }
/// Creates a duration from the specified number of microseconds /// Creates a duration from the specified number of microseconds, rounding down.
/// NOTE: Delays this small may be inaccurate. /// NOTE: Delays this small may be inaccurate.
pub const fn from_micros(micros: u64) -> Duration { pub const fn from_micros_floor(micros: u64) -> Duration {
Duration { Duration {
ticks: micros * (TICKS_PER_SECOND / GCD_1M) / (1_000_000 / GCD_1M), ticks: micros * (TICKS_PER_SECOND / GCD_1M) / (1_000_000 / GCD_1M),
} }
@ -155,3 +177,8 @@ impl<'a> fmt::Display for Duration {
write!(f, "{} ticks", self.ticks) write!(f, "{} ticks", self.ticks)
} }
} }
#[inline]
const fn div_ceil(num: u64, den: u64) -> u64 {
(num + den - 1) / den
}