Skip to content

Commit 44d5aed

Browse files
Make WASM polyfilled Instant work in web workers.
1 parent 8575691 commit 44d5aed

File tree

2 files changed

+11
-12
lines changed

2 files changed

+11
-12
lines changed

Diff for: akaze/Cargo.toml

+3-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,9 @@ serde = { version = "1.0", default-features = false, features = ["derive"], opti
3131
rayon = { version = "1.7.0", optional = true }
3232

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

3638
[dev-dependencies]
3739
eight-point = { version = "0.8.0", path = "../eight-point" }

Diff for: akaze/src/lib.rs

+8-11
Original file line numberDiff line numberDiff line change
@@ -27,24 +27,21 @@ impl Instant {
2727
fn now() -> Self {
2828
#[cfg(feature = "web-sys")]
2929
{
30-
Self(web_sys::window().unwrap().performance().unwrap().now())
30+
use wasm_bindgen::JsCast;
31+
let now = js_sys::global()
32+
.dyn_into::<web_sys::WorkerGlobalScope>()
33+
.and_then(|w| w.performance())
34+
.or_else(|| web_sys::window().and_then(|w| w.performance()))
35+
.map_or(0., |p| p.now());
36+
Self(now)
3137
}
3238
#[cfg(not(feature = "web-sys"))]
3339
{
3440
Self(0.)
3541
}
3642
}
3743
fn elapsed(&self) -> std::time::Duration {
38-
#[cfg(feature = "web-sys")]
39-
{
40-
std::time::Duration::from_secs_f64(
41-
(web_sys::window().unwrap().performance().unwrap().now() - self.0) * 0.001,
42-
)
43-
}
44-
#[cfg(not(feature = "web-sys"))]
45-
{
46-
std::time::Duration::from_secs(0)
47-
}
44+
std::time::Duration::from_secs_f64((Self::now().0 - self.0) * 0.001)
4845
}
4946
}
5047

0 commit comments

Comments
 (0)