Skip to main content

hick_embassy/
time.rs

1//! Bridge the `embassy-time` clock to the [`mdns_proto::Instant`] trait.
2
3use core::time::Duration;
4
5use embassy_time::{Duration as EmbassyDuration, Instant as RawInstant};
6use mdns_proto::Instant as ProtoInstant;
7
8/// An [`embassy_time::Instant`] that implements [`mdns_proto::Instant`].
9///
10/// `embassy_time::Instant` and the `mdns_proto::Instant` trait are both foreign
11/// here, so the orphan rule requires a newtype. The driver wraps each
12/// `Instant::now()` reading; the engine is generic over the trait, so this is
13/// the `I` type for the embassy path.
14#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
15pub struct EmbassyInstant(pub RawInstant);
16
17impl From<RawInstant> for EmbassyInstant {
18  #[inline(always)]
19  fn from(raw: RawInstant) -> Self {
20    Self(raw)
21  }
22}
23
24impl From<EmbassyInstant> for RawInstant {
25  #[inline(always)]
26  fn from(wrapped: EmbassyInstant) -> Self {
27    wrapped.0
28  }
29}
30
31impl ProtoInstant for EmbassyInstant {
32  #[inline]
33  fn checked_add_duration(self, dur: Duration) -> Option<Self> {
34    let micros = u64::try_from(dur.as_micros()).ok()?;
35    self
36      .0
37      .checked_add(EmbassyDuration::from_micros(micros))
38      .map(Self)
39  }
40
41  #[inline]
42  fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
43    let delta = self.0.checked_duration_since(earlier.0)?;
44    Some(Duration::from_micros(delta.as_micros()))
45  }
46}
47
48#[cfg(test)]
49#[allow(clippy::unwrap_used)]
50mod tests;