Skip to content

Commit

Permalink
Fix wasm non-web usage of env::now (#123)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bnjbvr authored Jan 30, 2023
1 parent 3cb9eac commit b9b4e6e
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions puffin/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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"))]
Expand All @@ -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<ProfilerScope> on the stack (None when profiling is off).
Expand Down

0 comments on commit b9b4e6e

Please sign in to comment.