Merge #1209
1209: Time: Add from_hz function for Duration. r=Dirbaio a=CBJamo I found myself doing things like this ```rust let rate_us = 1_000_000 / rate_hz; let mut ticker = Ticker::every(Duration::from_micros(rate_us)); ``` Several times, and figured it was worth adding a little convenience function to handle that. This also makes the calculation const, which is a nice little upside. The compiler might have been doing that already, but this makes sure. Speaking of const, would it be better to give hz as a float? Obviously we'd want to avoid that at runtime since many targets don't have a fpu, but if it's at compile time that doesn't matter and a float may be more ergonomic. Co-authored-by: Caleb Jamison <caleb@cbjamo.com>
This commit is contained in:
commit
023b0d5b22
@ -81,6 +81,20 @@ impl Duration {
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a duration corresponding to the specified Hz.
|
||||
/// NOTE: Giving this function a hz >= the TICK_HZ of your platform will clamp the Duration to 1
|
||||
/// tick. Doing so will not deadlock, but will certainly not produce the desired output.
|
||||
pub const fn from_hz(hz: u64) -> Duration {
|
||||
let ticks = {
|
||||
if hz >= TICK_HZ {
|
||||
1
|
||||
} else {
|
||||
(TICK_HZ + hz / 2) / hz
|
||||
}
|
||||
};
|
||||
Duration { ticks }
|
||||
}
|
||||
|
||||
/// Adds one Duration to another, returning a new Duration or None in the event of an overflow.
|
||||
pub fn checked_add(self, rhs: Duration) -> Option<Duration> {
|
||||
self.ticks.checked_add(rhs.ticks).map(|ticks| Duration { ticks })
|
||||
|
Loading…
Reference in New Issue
Block a user