1 // Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. 2 // Copyright by contributors to this project. 3 // SPDX-License-Identifier: (Apache-2.0 OR MIT) 4 5 use core::time::Duration; 6 7 #[cfg(target_arch = "wasm32")] 8 use 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)] 14 pub struct MlsTime { 15 seconds: u64, 16 } 17 18 impl MlsTime { 19 /// Create a timestamp from a duration since unix epoch. from_duration_since_epoch(duration: Duration) -> MlsTime20 pub fn from_duration_since_epoch(duration: Duration) -> MlsTime { 21 Self { 22 seconds: duration.as_secs(), 23 } 24 } 25 26 /// Number of seconds since the unix epoch. seconds_since_epoch(&self) -> u6427 pub fn seconds_since_epoch(&self) -> u64 { 28 self.seconds 29 } 30 } 31 32 #[cfg(all(not(target_arch = "wasm32"), feature = "std"))] 33 impl MlsTime { 34 /// Current system time. now() -> Self35 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 45 impl From<u64> for MlsTime { from(value: u64) -> Self46 fn from(value: u64) -> Self { 47 Self { seconds: value } 48 } 49 } 50 51 #[cfg(target_arch = "wasm32")] 52 #[wasm_bindgen(inline_js = r#" 53 export function date_now() { 54 return Date.now(); 55 }"#)] 56 extern "C" { date_now() -> f6457 fn date_now() -> f64; 58 } 59 60 #[cfg(target_arch = "wasm32")] 61 impl MlsTime { now() -> Self62 pub fn now() -> Self { 63 Self { 64 seconds: (date_now() / 1000.0) as u64, 65 } 66 } 67 } 68