common: Add support for obtaining the system time in wasm + JS environments

This commit is contained in:
Jonas Platte 2022-04-19 20:07:05 +02:00 committed by Jonas Platte
parent d32d60c868
commit dc692e7c16
2 changed files with 20 additions and 2 deletions

View File

@ -23,6 +23,7 @@ server = []
api = ["http", "thiserror"] api = ["http", "thiserror"]
compat = ["ruma-macros/compat", "ruma-identifiers-validation/compat"] compat = ["ruma-macros/compat", "ruma-identifiers-validation/compat"]
events = ["indoc", "thiserror"] events = ["indoc", "thiserror"]
js = ["js-sys"]
markdown = ["pulldown-cmark"] markdown = ["pulldown-cmark"]
rand = ["rand_crate", "uuid"] rand = ["rand_crate", "uuid"]
unstable-exhaustive-types = [] unstable-exhaustive-types = []
@ -65,6 +66,9 @@ url = "2.2.2"
uuid = { version = "1.0.0", optional = true, features = ["v4"] } uuid = { version = "1.0.0", optional = true, features = ["v4"] }
wildmatch = "2.0.0" wildmatch = "2.0.0"
[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies]
js-sys = { version = "0.3", optional = true }
[dev-dependencies] [dev-dependencies]
assign = "1.1.1" assign = "1.1.1"
http = "0.2.2" http = "0.2.2"

View File

@ -23,7 +23,11 @@ impl MilliSecondsSinceUnixEpoch {
/// The current system time in milliseconds since the unix epoch. /// The current system time in milliseconds since the unix epoch.
pub fn now() -> Self { 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. /// 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. /// The current system-time as seconds since the unix epoch.
pub fn now() -> Self { 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. /// 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)] #[cfg(test)]
mod tests { mod tests {
use std::time::{Duration, UNIX_EPOCH}; use std::time::{Duration, UNIX_EPOCH};