pub use core::time::Duration;
use std::time::SystemTimeError;
use thiserror::Error;
#[derive(Debug, Error)]
pub enum Error {
#[error("Failed to compute seconds since the unix epoch")]
TimeSinceUnixEpochError(#[from] SystemTimeError),
#[error("Failed to compute seconds since the unix epoch")]
NegativeTimestamp,
}
#[cfg(target_arch = "wasm32")]
mod wasm {
use super::{Duration, Error};
use wasm_bindgen::prelude::wasm_bindgen;
#[wasm_bindgen]
extern "C" {
type Date;
#[wasm_bindgen(static_method_of = Date)]
fn now() -> f64;
}
pub fn epoch() -> Result<Duration, Error> {
let signed_js_ts = Date::now() as i64;
let js_ms = signed_js_ts
.try_into()
.map_err(|_| Error::NegativeTimestamp)?;
Ok(Duration::from_millis(js_ms))
}
}
#[cfg(target_arch = "wasm32")]
pub use wasm::*;
#[cfg(not(target_arch = "wasm32"))]
pub fn epoch() -> Result<Duration, Error> {
Ok(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH)?)
}