From b9b4e6e780b12c206c71adc1114f5f02c21f5009 Mon Sep 17 00:00:00 2001 From: Benjamin Bouvier Date: Mon, 30 Jan 2023 21:00:06 +0100 Subject: [PATCH] Fix wasm non-web usage of env::now (#123) A wasm embedder that hasn't enabled the `web` feature will still get the `Instant::now()` function generated, even if they end up using a custom `now` function. After all, the compiler/link don't have runtime knowledge about how the program runs, so it could be that `ThreadProfiler::initialize` is never called, so the default value of `now_ns` that makes use of `Instant::now` could be called at any point. This changes the `now_ns` function so it's defined only using `Instant` for native target and wasm when web is enabled. In the other case, we assume this is never called and it's a programmer error because we don't have any time reporter. Fixes #118. --- puffin/src/lib.rs | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/puffin/src/lib.rs b/puffin/src/lib.rs index 3e4f5ad1..a6dd4b88 100644 --- a/puffin/src/lib.rs +++ b/puffin/src/lib.rs @@ -535,17 +535,11 @@ impl GlobalProfiler { /// Returns a high-precision, monotonically increasing nanosecond count since unix epoch. #[inline] +#[cfg(any(not(target_arch = "wasm32"), feature = "web"))] pub fn now_ns() -> NanoSecond { #[cfg(target_arch = "wasm32")] fn nanos_since_epoch() -> NanoSecond { - #[cfg(feature = "web")] - { - (js_sys::Date::new_0().get_time() * 1e6) as _ - } - #[cfg(not(feature = "web"))] - { - 0 // We won't get correct date-times, but that's fine. - } + (js_sys::Date::new_0().get_time() * 1e6) as _ } #[cfg(not(target_arch = "wasm32"))] @@ -566,6 +560,13 @@ pub fn now_ns() -> NanoSecond { START_TIME.0 + START_TIME.1.elapsed().as_nanos() as NanoSecond } +#[inline] +#[cfg(all(target_arch = "wasm32", not(feature = "web")))] +pub fn now_ns() -> NanoSecond { + // This should be unused. + panic!("Wasm without the `web` feature requires passing a custom source of time via `ThreadProfiler::initialize`"); +} + // ---------------------------------------------------------------------------- // We currently store an Option on the stack (None when profiling is off).