1 #![deny(unsafe_op_in_unsafe_fn)]
3 use crate::time::Duration;
5 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
6 pub struct Instant(Duration);
8 #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)]
9 pub struct SystemTime(Duration);
11 pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0));
13 fn current_time(clock: wasi::Clockid) -> Duration {
16 clock, 1, // precision... seems ignored though?
20 Duration::new((ts / 1_000_000_000) as u64, (ts % 1_000_000_000) as u32)
24 pub fn now() -> Instant {
25 Instant(current_time(wasi::CLOCKID_MONOTONIC))
28 pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> {
29 self.0.checked_sub(other.0)
32 pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> {
33 Some(Instant(self.0.checked_add(*other)?))
36 pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> {
37 Some(Instant(self.0.checked_sub(*other)?))
42 pub fn now() -> SystemTime {
43 SystemTime(current_time(wasi::CLOCKID_REALTIME))
46 pub fn from_wasi_timestamp(ts: wasi::Timestamp) -> SystemTime {
47 SystemTime(Duration::from_nanos(ts))
50 pub fn to_wasi_timestamp(&self) -> Option<wasi::Timestamp> {
51 self.0.as_nanos().try_into().ok()
54 pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> {
55 self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0)
58 pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> {
59 Some(SystemTime(self.0.checked_add(*other)?))
62 pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> {
63 Some(SystemTime(self.0.checked_sub(*other)?))