diff --git a/src/lib.rs b/src/lib.rs index 3e4caaf..f3c5031 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -28,6 +28,19 @@ pub use crate::native::now; #[cfg(feature = "now")] pub use crate::wasm::now; +#[cfg(any( +not(any(target_arch = "wasm32", target_arch = "asmjs")), +not(any(feature = "stdweb", feature = "wasm-bindgen")) +))] +pub use crate::native::SystemTime; + +#[cfg(all( +any(target_arch = "wasm32", target_arch = "asmjs"), +any(feature = "stdweb", feature = "wasm-bindgen") +))] +pub use crate::wasm::SystemTime; + + pub use std::time::Duration; #[cfg(any( diff --git a/src/native.rs b/src/native.rs index 37d5da4..7deefb6 100644 --- a/src/native.rs +++ b/src/native.rs @@ -1,4 +1,5 @@ pub type Instant = std::time::Instant; +pub type SystemTime = std::time::SystemTime; /// The current time, in milliseconds. #[cfg(feature = "now")] diff --git a/src/wasm.rs b/src/wasm.rs index 24a6b7c..d0e12f7 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -101,3 +101,62 @@ pub fn now() -> f64 { .expect("performance should be available") .now() } + +#[derive(Copy, Clone, Debug, PartialEq, PartialOrd)] +pub struct SystemTime(f64); + +impl SystemTime { + pub const UNIX_EPOCH: SystemTime = SystemTime(0.0); + + pub fn now() -> SystemTime { + SystemTime(now()) + } + + pub fn duration_since(&self, earlier: SystemTime) -> Result { + let dur_ms = self.0 - earlier.0; + if dur_ms < 0.0 { + return Err(()) + } + Ok(Duration::from_millis(dur_ms as u64)) + } + + pub fn elapsed(&self) -> Result { + self.duration_since(SystemTime::now()) + } + + pub fn checked_add(&self, duration: Duration) -> Option { + Some(*self + duration) + } + + pub fn checked_sub(&self, duration: Duration) -> Option { + Some(*self - duration) + } +} + +impl Add for SystemTime { + type Output = SystemTime; + + fn add(self, other: Duration) -> SystemTime { + SystemTime(self.0 + other.as_millis() as f64) + } +} + +impl Sub for SystemTime { + type Output = SystemTime; + + fn sub(self, other: Duration) -> SystemTime { + SystemTime(self.0 - other.as_millis() as f64) + } +} + +impl AddAssign for SystemTime { + fn add_assign(&mut self, rhs: Duration) { + *self = *self + rhs; + } +} + +impl SubAssign for SystemTime { + fn sub_assign(&mut self, rhs: Duration) { + *self = *self - rhs; + } +} diff --git a/tests/wasm.rs b/tests/wasm.rs index f5bfe93..e8a92ff 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -1,6 +1,6 @@ extern crate wasm_bindgen_test; -use instant::Instant; +use instant::{Instant, SystemTime}; use std::time::Duration; use wasm_bindgen_test::*; @@ -19,3 +19,12 @@ fn test_duration() { let one_sec = Duration::from_secs(1); assert!(now.elapsed() < one_sec); } + +#[wasm_bindgen_test] +fn test_system_time() { + assert!( + SystemTime::UNIX_EPOCH + .duration_since(SystemTime::now()) + .is_err() + ); +}