Merge pull request #4695 from meowcakes/time-as-nanos

Add `as_nanos` and `from_nanos` where missing in embassy-time
This commit is contained in:
Dario Nieuwenhuis 2025-09-22 11:01:27 +00:00 committed by GitHub
commit de5dd10a58
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 31 additions and 1 deletions

View File

@ -8,6 +8,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
<!-- next-header -->
## Unreleased - ReleaseDate
- Add as_nanos and from_nanos where missing
## 0.5.0 - 2025-08-26
- Allow inlining on time driver boundary

View File

@ -37,6 +37,11 @@ impl Duration {
self.ticks * (1_000_000 / GCD_1M) / (TICK_HZ / GCD_1M)
}
/// Convert the `Duration` to nanoseconds, rounding down.
pub const fn as_nanos(&self) -> u64 {
self.ticks * (1_000_000_000 / GCD_1G) / (TICK_HZ / GCD_1G)
}
/// Creates a duration from the specified number of clock ticks
pub const fn from_ticks(ticks: u64) -> Duration {
Duration { ticks }

View File

@ -1,7 +1,7 @@
use core::fmt;
use core::ops::{Add, AddAssign, Sub, SubAssign};
use super::{Duration, GCD_1K, GCD_1M, TICK_HZ};
use super::{Duration, GCD_1G, GCD_1K, GCD_1M, TICK_HZ};
#[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
@ -29,6 +29,13 @@ impl Instant {
Self { ticks }
}
/// Create an Instant from a nanosecond count since system boot.
pub const fn from_nanos(nanos: u64) -> Self {
Self {
ticks: nanos * (TICK_HZ / GCD_1G) / (1_000_000_000 / GCD_1G),
}
}
/// Create an Instant from a microsecond count since system boot.
pub const fn from_micros(micros: u64) -> Self {
Self {
@ -50,6 +57,17 @@ impl Instant {
}
}
/// Try to create an Instant from a nanosecond count since system boot.
/// Fails if the number of nanoseconds is too large.
pub const fn try_from_nanos(nanos: u64) -> Option<Self> {
let Some(value) = nanos.checked_mul(TICK_HZ / GCD_1G) else {
return None;
};
Some(Self {
ticks: value / (1_000_000_000 / GCD_1G),
})
}
/// Try to create an Instant from a microsecond count since system boot.
/// Fails if the number of microseconds is too large.
pub const fn try_from_micros(micros: u64) -> Option<Self> {
@ -101,6 +119,11 @@ impl Instant {
self.ticks * (1_000_000 / GCD_1M) / (TICK_HZ / GCD_1M)
}
/// Nanoseconds since system boot.
pub const fn as_nanos(&self) -> u64 {
self.ticks * (1_000_000_000 / GCD_1G) / (TICK_HZ / GCD_1G)
}
/// Duration between this Instant and another Instant
/// Panics on over/underflow.
pub fn duration_since(&self, earlier: Instant) -> Duration {