Skip to content

Commit

Permalink
fix: replace std::time:SystemTime with web_time::SystemTime
Browse files Browse the repository at this point in the history
Allows consistent usage of SystemTime between targets (including WASM)
  • Loading branch information
karpfediem committed Jan 15, 2024
1 parent da8e406 commit b7109ff
Show file tree
Hide file tree
Showing 3 changed files with 4 additions and 17 deletions.
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ lexical-core = { version = "0.8.5", default-features = false, features = [
reqwest = { version = "0.11", features = ["blocking", "json"], optional = true }
tabled = { version = "0.15.0", optional = true }
openssl = { version = "0.10", features = ["vendored"], optional = true }
web-time = { version = "1.0.0" }

[target.wasm32-unknown-unknown.dependencies]
js-sys = { version = "0.3" }
Expand Down
18 changes: 2 additions & 16 deletions src/system_time.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,8 @@
use crate::{Duration, Errors};

#[cfg(target_arch = "wasm32")]
pub(crate) fn duration_since_unix_epoch() -> Result<Duration, Errors> {
{
use crate::Unit;
use wasm_bindgen_rs::prelude::*;
js_sys::Reflect::get(&js_sys::global(), &JsValue::from_str("performance"))
.map_err(|_| Errors::SystemTimeError)
.map(|performance| {
performance.unchecked_into::<web_sys::Performance>().now() * Unit::Second
})
}
}

#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn duration_since_unix_epoch() -> Result<Duration, Errors> {
std::time::SystemTime::now()
.duration_since(std::time::SystemTime::UNIX_EPOCH)
web_time::SystemTime::now()
.duration_since(web_time::SystemTime::UNIX_EPOCH)
.map_err(|_| Errors::SystemTimeError)
.and_then(|d| d.try_into().map_err(|_| Errors::SystemTimeError))
}
2 changes: 1 addition & 1 deletion tests/epoch.rs
Original file line number Diff line number Diff line change
Expand Up @@ -526,7 +526,7 @@ fn unix() {
// Continuous check that the system time as reported by this machine is within millisecond accuracy of what we compute
#[cfg(feature = "std")]
{
use std::time::SystemTime;
use web_time::SystemTime;

let std_unix_time_s = SystemTime::now()
.duration_since(SystemTime::UNIX_EPOCH)
Expand Down

0 comments on commit b7109ff

Please sign in to comment.