|
| 1 | +use crate::os::xous::ffi::blocking_scalar; |
| 2 | +use crate::os::xous::services::{ |
| 3 | + systime_server, ticktimer_server, SystimeScalar::GetUtcTimeMs, TicktimerScalar::ElapsedMs, |
| 4 | +}; |
| 5 | +use crate::time::Duration; |
| 6 | + |
| 7 | +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] |
| 8 | +pub struct Instant(Duration); |
| 9 | + |
| 10 | +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Hash)] |
| 11 | +pub struct SystemTime(Duration); |
| 12 | + |
| 13 | +pub const UNIX_EPOCH: SystemTime = SystemTime(Duration::from_secs(0)); |
| 14 | + |
| 15 | +impl Instant { |
| 16 | + pub fn now() -> Instant { |
| 17 | + let result = blocking_scalar(ticktimer_server(), ElapsedMs.into()) |
| 18 | + .expect("failed to request elapsed_ms"); |
| 19 | + let lower = result[0]; |
| 20 | + let upper = result[1]; |
| 21 | + Instant { 0: Duration::from_millis(lower as u64 | (upper as u64) << 32) } |
| 22 | + } |
| 23 | + |
| 24 | + pub fn checked_sub_instant(&self, other: &Instant) -> Option<Duration> { |
| 25 | + self.0.checked_sub(other.0) |
| 26 | + } |
| 27 | + |
| 28 | + pub fn checked_add_duration(&self, other: &Duration) -> Option<Instant> { |
| 29 | + self.0.checked_add(*other).map(Instant) |
| 30 | + } |
| 31 | + |
| 32 | + pub fn checked_sub_duration(&self, other: &Duration) -> Option<Instant> { |
| 33 | + self.0.checked_sub(*other).map(Instant) |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +impl SystemTime { |
| 38 | + pub fn now() -> SystemTime { |
| 39 | + let result = blocking_scalar(systime_server(), GetUtcTimeMs.into()) |
| 40 | + .expect("failed to request utc time in ms"); |
| 41 | + let lower = result[0]; |
| 42 | + let upper = result[1]; |
| 43 | + SystemTime { 0: Duration::from_millis((upper as u64) << 32 | lower as u64) } |
| 44 | + } |
| 45 | + |
| 46 | + pub fn sub_time(&self, other: &SystemTime) -> Result<Duration, Duration> { |
| 47 | + self.0.checked_sub(other.0).ok_or_else(|| other.0 - self.0) |
| 48 | + } |
| 49 | + |
| 50 | + pub fn checked_add_duration(&self, other: &Duration) -> Option<SystemTime> { |
| 51 | + Some(SystemTime(self.0.checked_add(*other)?)) |
| 52 | + } |
| 53 | + |
| 54 | + pub fn checked_sub_duration(&self, other: &Duration) -> Option<SystemTime> { |
| 55 | + Some(SystemTime(self.0.checked_sub(*other)?)) |
| 56 | + } |
| 57 | +} |
0 commit comments