From a0a204f586301ee4e014c3673c2ecd3ad90c504c Mon Sep 17 00:00:00 2001 From: Rogan Morrow Date: Mon, 22 Sep 2025 13:36:22 +1000 Subject: add as_nanos and from_nanos where missing --- embassy-time/src/duration.rs | 5 +++++ embassy-time/src/instant.rs | 14 +++++++++++++- 2 files changed, 18 insertions(+), 1 deletion(-) (limited to 'embassy-time') diff --git a/embassy-time/src/duration.rs b/embassy-time/src/duration.rs index 5b140eeff..b3ea0468d 100644 --- a/embassy-time/src/duration.rs +++ b/embassy-time/src/duration.rs @@ -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 } diff --git a/embassy-time/src/instant.rs b/embassy-time/src/instant.rs index 6571bea62..a311b365c 100644 --- a/embassy-time/src/instant.rs +++ b/embassy-time/src/instant.rs @@ -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_1K, GCD_1M, GCD_1G, 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 { @@ -101,6 +108,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 { -- cgit