ferravex_net/
time.rs

1//! Transport clock shared by native sockets and browser hosts. Browser hosts
2//! explicitly supply monotonic microseconds; no unsupported Wasm OS clock call.
3#[cfg(target_arch = "wasm32")]
4use std::cell::Cell;
5use std::time::Duration;
6#[cfg(target_arch = "wasm32")]
7thread_local! {static NOW:Cell<u64>=const{Cell::new(0)};}
8#[cfg(target_arch = "wasm32")]
9pub fn set_browser_time(micros: u64) -> bool {
10    NOW.with(|now| {
11        if micros > 1 << 53 || micros < now.get() {
12            return false;
13        }
14        now.set(micros);
15        true
16    })
17}
18#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
19pub struct Instant(i128);
20impl Instant {
21    pub fn now() -> Self {
22        #[cfg(not(target_arch = "wasm32"))]
23        {
24            static ORIGIN: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
25            Self(
26                ORIGIN
27                    .get_or_init(std::time::Instant::now)
28                    .elapsed()
29                    .as_micros()
30                    .min((1u128 << 53) - 1) as i128,
31            )
32        }
33        #[cfg(target_arch = "wasm32")]
34        Self(i128::from(NOW.with(Cell::get)))
35    }
36    pub fn as_micros(self) -> u64 {
37        self.0.max(0) as u64
38    }
39    pub fn elapsed(self) -> Duration {
40        Self::now().saturating_duration_since(self)
41    }
42    pub fn duration_since(self, earlier: Self) -> Duration {
43        self.saturating_duration_since(earlier)
44    }
45    pub fn saturating_duration_since(self, earlier: Self) -> Duration {
46        Duration::from_micros((self.0 - earlier.0).clamp(0, i128::from(u64::MAX)) as u64)
47    }
48}
49impl std::ops::Sub<Duration> for Instant {
50    type Output = Self;
51    fn sub(self, rhs: Duration) -> Self {
52        Self(self.0 - rhs.as_micros().min(i128::MAX as u128) as i128)
53    }
54}
55impl std::ops::Add<Duration> for Instant {
56    type Output = Self;
57    fn add(self, rhs: Duration) -> Self {
58        Self(self.0 + rhs.as_micros().min(i128::MAX as u128) as i128)
59    }
60}