Skip to content

Commit

Permalink
use Date::now for SystemTime::now
Browse files Browse the repository at this point in the history
  • Loading branch information
wngr committed Oct 1, 2021
1 parent c59ec90 commit bd46ccb
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 13 deletions.
14 changes: 2 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,24 +11,14 @@ cfg_if::cfg_if! {
pub use wasm::Instant;
#[cfg(feature = "now")]
pub use crate::wasm::now;
pub use wasm::SystemTime;
} else {
mod native;
pub use native::Instant;
#[cfg(feature = "now")]
pub use native::now;
pub use native::SystemTime;
}
}

#[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;
20 changes: 19 additions & 1 deletion src/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -162,14 +162,32 @@ pub fn now() -> f64 {
return unsafe { js::_emscripten_get_now() };
}

/// Returns the number of millisecods elapsed since January 1, 1970 00:00:00 UTC.
#[cfg(any(feature = "wasm-bindgen", feature = "stdweb"))]
fn get_time() -> f64 {
#[cfg(feature = "wasm-bindgen")]
return js_sys::Date::now();
#[cfg(all(feature = "stdweb", not(feature = "wasm-bindgen")))]
{
let v = js! { return Date.now(); };
return v.try_into().unwrap();
}
}

#[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())
cfg_if::cfg_if! {
if #[cfg(any(feature = "wasm-bindgen", feature = "stdweb"))] {
SystemTime(get_time())
} else {
SystemTime(now())
}
}
}

pub fn duration_since(&self, earlier: SystemTime) -> Result<Duration, ()> {
Expand Down
1 change: 1 addition & 0 deletions tests/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,3 +54,4 @@ fn test_system_time() {
.duration_since(SystemTime::now())
.is_err());
}

0 comments on commit bd46ccb

Please sign in to comment.