Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use global() to get performance API on wasm32-unknown-unknown #107

Merged
merged 5 commits into from
Dec 12, 2024
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 17 additions & 8 deletions src/clocks/monotonic/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
const WASM_WRONG_ENV: &str = "failed to find the global `window` object: the `wasm32-unknown-unknown` implementation only supports running in web browsers; wse `wasm32-wasi` to run elsewhere";
const WASM_MISSING_WINDOW_PERF: &str = "failed to find `window.performance`";
use web_sys::{
js_sys::Reflect,
wasm_bindgen::{JsCast, JsValue},
Performance,
};

const WASM_MISSING_GLOBAL_THIS_PERF: &str = "failed to find `globalThis.performance`";
const WASM_UNABLE_TO_CAST_PERF: &str =
"Unable to cast `globalThis.performance` to Performance type";
#[derive(Clone, Copy, Debug, Default)]
pub struct Monotonic {
_default: (),
Expand All @@ -9,12 +15,15 @@ pub struct Monotonic {
#[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
impl Monotonic {
pub fn now(&self) -> u64 {
let now = web_sys::window()
.expect(WASM_WRONG_ENV)
.performance()
.expect(WASM_MISSING_WINDOW_PERF)
.now();
// `window.performance.now()` returns the time in milliseconds.
let now = Reflect::get(
&web_sys::js_sys::global(),
&JsValue::from_str("performance"),
)
.expect(WASM_MISSING_GLOBAL_THIS_PERF)
.dyn_ref::<Performance>()
.expect(WASM_UNABLE_TO_CAST_PERF)
.now();
// `performance.now()` returns the time in milliseconds.
return f64::trunc(now * 1_000_000.0) as u64;
}
}
Expand Down