From 73239d1b0c00fa7b1fc03032e8b4d7c95273b5a5 Mon Sep 17 00:00:00 2001 From: Michael Pfaff Date: Sat, 28 May 2022 13:54:36 -0400 Subject: [PATCH] Add Instant --- Cargo.toml | 3 ++- src/lib.rs | 40 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Cargo.toml b/Cargo.toml index 5194697..51375ee 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -10,5 +10,6 @@ local-offset = [ "time/local-offset" ] time = "0.3" [target.'cfg(target_arch = "wasm32")'.dependencies] -js-sys = "0.3.57" +js-sys = { version = "0.3.57", default-features = false } +web-sys = { version = "0.3.57", default-features = false, features = [ "Window", "Performance" ] } diff --git a/src/lib.rs b/src/lib.rs index 96dc7ea..b634d00 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,3 +1,4 @@ +use time::Duration; use time::OffsetDateTime; #[cfg(target_arch = "wasm32")] @@ -12,6 +13,45 @@ pub fn now_utc() -> OffsetDateTime { return OffsetDateTime::now_utc(); } +#[cfg(target_arch = "wasm32")] +type InnerInstant = Duration; +#[cfg(not(target_arch = "wasm32"))] +type InnerInstant = time::Instant; + +/// On wasm32, represented as a [`Duration`] from an arbitrary epoch. On other architectures, +/// represented as [`time::Instant`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +#[repr(transparent)] +pub struct Instant(InnerInstant); + +impl Instant { + #[cfg(target_arch = "wasm32")] + pub fn now() -> Instant { + let stamp = web_sys::window().expect("cannot get window").performance().expect("cannot get performance").now(); + return Instant(Duration::seconds_f64(stamp / 1_000f64)); + } + + #[cfg(not(target_arch = "wasm32"))] + #[inline(always)] + pub fn now() -> Instant { + return Instant(time::Instant::now()); + } + + #[inline(always)] + pub fn elapsed(self) -> Duration { + Self::now() - self + } +} + +impl std::ops::Sub for Instant { + type Output = Duration; + + #[inline(always)] + fn sub(self, rhs: Self) -> Self::Output { + self.0 - rhs.0 + } +} + #[cfg(feature = "local-offset")] #[cfg(target_arch = "wasm32")] pub fn current_local_offset() -> Result {