Skip to content

Commit

Permalink
Make WASM polyfilled Instant work in web workers.
Browse files Browse the repository at this point in the history
  • Loading branch information
stephanemagnenat committed Jul 20, 2023
1 parent 8575691 commit 8b68e54
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 12 deletions.
4 changes: 3 additions & 1 deletion akaze/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,9 @@ serde = { version = "1.0", default-features = false, features = ["derive"], opti
rayon = { version = "1.7.0", optional = true }

[target.'cfg(target_arch = "wasm32")'.dependencies]
web-sys = { version = "0.3.64", features = ["Window", "Performance"], optional = true }
wasm-bindgen = "0.2.87"
js-sys = "0.3.64"
web-sys = { version = "0.3.64", features = ["Window", "Performance", "WorkerGlobalScope"], optional = true }

[dev-dependencies]
eight-point = { version = "0.8.0", path = "../eight-point" }
Expand Down
19 changes: 8 additions & 11 deletions akaze/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,24 +27,21 @@ impl Instant {
fn now() -> Self {
#[cfg(feature = "web-sys")]
{
Self(web_sys::window().unwrap().performance().unwrap().now())
use wasm_bindgen::JsCast;
let now = js_sys::global()
.dyn_into::<web_sys::WorkerGlobalScope>()
.and_then(|w| w.performance())
.or_else(|_| web_sys::window().and_then(|w| w.performance()))
.map_or(0., |p| p.now());
Self(now)
}
#[cfg(not(feature = "web-sys"))]
{
Self(0.)
}
}
fn elapsed(&self) -> std::time::Duration {
#[cfg(feature = "web-sys")]
{
std::time::Duration::from_secs_f64(
(web_sys::window().unwrap().performance().unwrap().now() - self.0) * 0.001,
)
}
#[cfg(not(feature = "web-sys"))]
{
std::time::Duration::from_secs(0)
}
std::time::Duration::from_secs_f64((Self::now().0 - self.0) * 0.001)
}
}

Expand Down

0 comments on commit 8b68e54

Please sign in to comment.