diff --git a/crates/ruma-common/Cargo.toml b/crates/ruma-common/Cargo.toml index 4f5b08f9..53cc55a5 100644 --- a/crates/ruma-common/Cargo.toml +++ b/crates/ruma-common/Cargo.toml @@ -23,6 +23,7 @@ server = [] api = ["http", "thiserror"] compat = ["ruma-macros/compat", "ruma-identifiers-validation/compat"] events = ["indoc", "thiserror"] +js = ["js-sys"] markdown = ["pulldown-cmark"] rand = ["rand_crate", "uuid"] unstable-exhaustive-types = [] @@ -65,6 +66,9 @@ url = "2.2.2" uuid = { version = "1.0.0", optional = true, features = ["v4"] } wildmatch = "2.0.0" +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] +js-sys = { version = "0.3", optional = true } + [dev-dependencies] assign = "1.1.1" http = "0.2.2" diff --git a/crates/ruma-common/src/time.rs b/crates/ruma-common/src/time.rs index 232da64d..f963dc37 100644 --- a/crates/ruma-common/src/time.rs +++ b/crates/ruma-common/src/time.rs @@ -23,7 +23,11 @@ impl MilliSecondsSinceUnixEpoch { /// The current system time in milliseconds since the unix epoch. pub fn now() -> Self { - Self::from_system_time(SystemTime::now()).unwrap() + #[cfg(not(all(target_arch = "wasm32", target_os = "unknown", feature = "js")))] + return Self::from_system_time(SystemTime::now()).unwrap(); + + #[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "js"))] + return Self(f64_to_uint(js_sys::Date::now())); } /// Creates a new `SystemTime` from `self`, if it can be represented. @@ -59,7 +63,11 @@ impl SecondsSinceUnixEpoch { /// The current system-time as seconds since the unix epoch. pub fn now() -> Self { - Self::from_system_time(SystemTime::now()).unwrap() + #[cfg(not(all(target_arch = "wasm32", target_os = "unknown", feature = "js")))] + return Self::from_system_time(SystemTime::now()).unwrap(); + + #[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "js"))] + return Self(f64_to_uint(js_sys::Date::now() / 1000.0)); } /// Creates a new `SystemTime` from `self`, if it can be represented. @@ -73,6 +81,12 @@ impl SecondsSinceUnixEpoch { } } +#[cfg(all(target_arch = "wasm32", target_os = "unknown", feature = "js"))] +fn f64_to_uint(val: f64) -> UInt { + use std::convert::TryFrom; + UInt::try_from(val as u64).unwrap() +} + #[cfg(test)] mod tests { use std::time::{Duration, UNIX_EPOCH};