Skip to main content

runmat_time/
lib.rs

1use std::time::{Duration, SystemTime, UNIX_EPOCH};
2
3#[cfg(target_arch = "wasm32")]
4use js_sys::Date;
5
6#[cfg(target_arch = "wasm32")]
7pub use instant::Instant;
8
9#[cfg(not(target_arch = "wasm32"))]
10pub use std::time::Instant;
11
12#[cfg(target_arch = "wasm32")]
13fn js_duration_since_epoch() -> Duration {
14    let millis = Date::now();
15    Duration::from_secs_f64(millis / 1000.0)
16}
17
18#[cfg(not(target_arch = "wasm32"))]
19fn native_duration_since_epoch() -> Duration {
20    SystemTime::now()
21        .duration_since(UNIX_EPOCH)
22        .unwrap_or(Duration::ZERO)
23}
24
25/// Returns a `SystemTime` representing "now" even on wasm targets where
26/// `SystemTime::now()` normally panics. On wasm we synthesize the timestamp
27/// from `Date.now()` so existing code can keep using standard APIs.
28pub fn system_time_now() -> SystemTime {
29    #[cfg(target_arch = "wasm32")]
30    {
31        UNIX_EPOCH + js_duration_since_epoch()
32    }
33    #[cfg(not(target_arch = "wasm32"))]
34    {
35        SystemTime::now()
36    }
37}
38
39/// Returns the duration since the Unix epoch for the current instant.
40pub fn duration_since_epoch() -> Duration {
41    #[cfg(target_arch = "wasm32")]
42    {
43        js_duration_since_epoch()
44    }
45    #[cfg(not(target_arch = "wasm32"))]
46    {
47        native_duration_since_epoch()
48    }
49}
50
51/// Milliseconds since the Unix epoch, safe to call on wasm and native hosts.
52pub fn unix_timestamp_ms() -> u128 {
53    duration_since_epoch().as_millis()
54}
55
56/// Microseconds since the Unix epoch.
57pub fn unix_timestamp_us() -> u128 {
58    duration_since_epoch().as_micros()
59}
60
61/// Nanoseconds since the Unix epoch.
62pub fn unix_timestamp_ns() -> u128 {
63    duration_since_epoch().as_nanos()
64}