From c023a97039a5549e0ad2549111c31b11d17c2cb1 Mon Sep 17 00:00:00 2001 From: Micha <61242418+modestmicha@users.noreply.github.com> Date: Wed, 18 Nov 2020 20:37:26 +0000 Subject: [PATCH] Add inaccurate time option For environments where `performance.now()` is not available such as Cloudflare Workers. --- Cargo.toml | 1 + README.md | 20 ++++++++++++++++++++ src/wasm.rs | 21 +++++++++++++++------ tests/wasm.rs | 3 +++ 4 files changed, 39 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 8a7047e..1f146ad 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ edition = "2018" [features] now = [ "time" ] wasm-bindgen = ["js-sys", "wasm-bindgen_rs", "web-sys"] +inaccurate = [] [dependencies] cfg-if = "1.0" diff --git a/README.md b/README.md index 28f6bdd..ecda215 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,26 @@ fn main() { } ``` +----- + +### Using `instant` for a WASM platform where `performance.now()` is not available. +This example shows the use of the `inaccurate` feature. + +_Cargo.toml_: +```toml +[dependencies] +instant = { version = "0.1", features = [ "wasm-bindgen", "inaccurate" ] } +``` + +_main.rs_: +```rust +fn main() { + // Will emulate `std::time::Instant` based on `Date.now()`. + let now = instant::Instant::new(); +} +``` + + ----- ### Using `instant` for any platform enabling a feature transitively. diff --git a/src/wasm.rs b/src/wasm.rs index 829ef3b..986bbf6 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -101,18 +101,27 @@ pub fn now() -> f64 { use stdweb::unstable::TryInto; // https://developer.mozilla.org/en-US/docs/Web/API/Performance/now + #[cfg(not(feature = "inaccurate"))] let v = js! { return performance.now(); }; + #[cfg(feature = "inaccurate")] + let v = js! { return Date.now(); }; v.try_into().unwrap() } #[cfg(feature = "wasm-bindgen")] pub fn now() -> f64 { - use wasm_bindgen_rs::prelude::*; - use wasm_bindgen_rs::JsCast; - js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance")) - .expect("failed to get performance from global object") - .unchecked_into::() - .now() + #[cfg(not(feature = "inaccurate"))] + let now = { + use wasm_bindgen_rs::prelude::*; + use wasm_bindgen_rs::JsCast; + js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance")) + .expect("failed to get performance from global object") + .unchecked_into::() + .now() + }; + #[cfg(feature = "inaccurate")] + let now = js_sys::Date::now(); + now } // The JS now function is in a module so it won't have to be renamed diff --git a/tests/wasm.rs b/tests/wasm.rs index b1577ad..863eefd 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -10,6 +10,9 @@ wasm_bindgen_test_configure!(run_in_browser); #[wasm_bindgen_test] fn test_instant_now() { let now = Instant::now(); + #[cfg(feature = "inaccurate")] + while now.elapsed().as_millis() == 0 {} + #[cfg(not(feature = "inaccurate"))] assert!(now.elapsed().as_nanos() > 0); }