1use core::time::Duration;
6
7#[cfg(target_arch = "wasm32")]
8use wasm_bindgen::prelude::*;
9
10#[cfg_attr(all(feature = "ffi", not(test)), safer_ffi_gen::ffi_type)]
11#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
12#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
13#[repr(transparent)]
14pub struct MlsTime {
15 seconds: u64,
16}
17
18impl MlsTime {
19 pub fn from_duration_since_epoch(duration: Duration) -> MlsTime {
21 Self {
22 seconds: duration.as_secs(),
23 }
24 }
25
26 pub fn seconds_since_epoch(&self) -> u64 {
28 self.seconds
29 }
30}
31
32#[cfg(all(not(target_arch = "wasm32"), feature = "std"))]
33impl MlsTime {
34 pub fn now() -> Self {
36 Self {
37 seconds: std::time::SystemTime::now()
38 .duration_since(std::time::SystemTime::UNIX_EPOCH)
39 .unwrap_or_default()
40 .as_secs(),
41 }
42 }
43}
44
45impl From<u64> for MlsTime {
46 fn from(value: u64) -> Self {
47 Self { seconds: value }
48 }
49}
50
51#[cfg(target_arch = "wasm32")]
52#[wasm_bindgen(inline_js = r#"
53export function date_now() {
54 return Date.now();
55}"#)]
56extern "C" {
57 fn date_now() -> f64;
58}
59
60#[cfg(target_arch = "wasm32")]
61impl MlsTime {
62 pub fn now() -> Self {
63 Self {
64 seconds: (date_now() / 1000.0) as u64,
65 }
66 }
67}