common: Add support for obtaining the system time in wasm + JS environments
This commit is contained in:
parent
d32d60c868
commit
dc692e7c16
@ -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"
|
||||
|
@ -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};
|
||||
|
Loading…
x
Reference in New Issue
Block a user