diff options
| author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2023-02-10 02:19:31 +0000 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-02-10 02:19:31 +0000 |
| commit | 023b0d5b2270f31aa69e54aa3d43416e16c33966 (patch) | |
| tree | 134e12f460be9660e7be3fb4dcf92a9a938d4de2 | |
| parent | e1a0df7d46419962b92c36d8efd8c4840eef7349 (diff) | |
| parent | bd7b3bd455fc5946a3944bd931acfdf255929cb6 (diff) | |
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 <[email protected]>
| -rw-r--r-- | embassy-time/src/duration.rs | 14 |
1 files changed, 14 insertions, 0 deletions
diff --git a/embassy-time/src/duration.rs b/embassy-time/src/duration.rs index d3c6f42a9..9d0bab2dd 100644 --- a/embassy-time/src/duration.rs +++ b/embassy-time/src/duration.rs | |||
| @@ -81,6 +81,20 @@ impl Duration { | |||
| 81 | } | 81 | } |
| 82 | } | 82 | } |
| 83 | 83 | ||
| 84 | /// Creates a duration corresponding to the specified Hz. | ||
| 85 | /// NOTE: Giving this function a hz >= the TICK_HZ of your platform will clamp the Duration to 1 | ||
| 86 | /// tick. Doing so will not deadlock, but will certainly not produce the desired output. | ||
| 87 | pub const fn from_hz(hz: u64) -> Duration { | ||
| 88 | let ticks = { | ||
| 89 | if hz >= TICK_HZ { | ||
| 90 | 1 | ||
| 91 | } else { | ||
| 92 | (TICK_HZ + hz / 2) / hz | ||
| 93 | } | ||
| 94 | }; | ||
| 95 | Duration { ticks } | ||
| 96 | } | ||
| 97 | |||
| 84 | /// Adds one Duration to another, returning a new Duration or None in the event of an overflow. | 98 | /// Adds one Duration to another, returning a new Duration or None in the event of an overflow. |
| 85 | pub fn checked_add(self, rhs: Duration) -> Option<Duration> { | 99 | pub fn checked_add(self, rhs: Duration) -> Option<Duration> { |
| 86 | self.ticks.checked_add(rhs.ticks).map(|ticks| Duration { ticks }) | 100 | self.ticks.checked_add(rhs.ticks).map(|ticks| Duration { ticks }) |
