|
| 1 | +use crate::p3::bindings::{ |
| 2 | + clocks::monotonic_clock::{self, Duration as WasiDuration, Instant}, |
| 3 | + clocks::wall_clock::{self, Datetime}, |
| 4 | +}; |
| 5 | +use crate::{WasiImpl, WasiView}; |
| 6 | +use cap_std::time::SystemTime; |
| 7 | +use std::time::Duration; |
| 8 | +use tokio::time::sleep; |
| 9 | + |
| 10 | +mod sync; |
| 11 | + |
| 12 | +impl TryFrom<SystemTime> for Datetime { |
| 13 | + type Error = anyhow::Error; |
| 14 | + |
| 15 | + fn try_from(time: SystemTime) -> Result<Self, Self::Error> { |
| 16 | + let duration = |
| 17 | + time.duration_since(SystemTime::from_std(std::time::SystemTime::UNIX_EPOCH))?; |
| 18 | + |
| 19 | + Ok(Self { |
| 20 | + seconds: duration.as_secs(), |
| 21 | + nanoseconds: duration.subsec_nanos(), |
| 22 | + }) |
| 23 | + } |
| 24 | +} |
| 25 | + |
| 26 | +impl<T> wall_clock::Host for WasiImpl<T> |
| 27 | +where |
| 28 | + T: WasiView, |
| 29 | +{ |
| 30 | + fn now(&mut self) -> anyhow::Result<Datetime> { |
| 31 | + let now = self.ctx().wall_clock.now(); |
| 32 | + Ok(Datetime { |
| 33 | + seconds: now.as_secs(), |
| 34 | + nanoseconds: now.subsec_nanos(), |
| 35 | + }) |
| 36 | + } |
| 37 | + |
| 38 | + fn resolution(&mut self) -> anyhow::Result<Datetime> { |
| 39 | + let res = self.ctx().wall_clock.resolution(); |
| 40 | + Ok(Datetime { |
| 41 | + seconds: res.as_secs(), |
| 42 | + nanoseconds: res.subsec_nanos(), |
| 43 | + }) |
| 44 | + } |
| 45 | +} |
| 46 | + |
| 47 | +impl<T> monotonic_clock::Host for WasiImpl<T> |
| 48 | +where |
| 49 | + T: WasiView, |
| 50 | +{ |
| 51 | + fn now(&mut self) -> anyhow::Result<Instant> { |
| 52 | + Ok(self.ctx().monotonic_clock.now()) |
| 53 | + } |
| 54 | + |
| 55 | + fn resolution(&mut self) -> anyhow::Result<Instant> { |
| 56 | + Ok(self.ctx().monotonic_clock.resolution()) |
| 57 | + } |
| 58 | + |
| 59 | + async fn wait_until(&mut self, when: Instant) -> anyhow::Result<()> { |
| 60 | + let clock_now = self.ctx().monotonic_clock.now(); |
| 61 | + if when > clock_now { |
| 62 | + sleep(Duration::from_nanos(when - clock_now)).await; |
| 63 | + }; |
| 64 | + Ok(()) |
| 65 | + } |
| 66 | + |
| 67 | + async fn wait_for(&mut self, duration: WasiDuration) -> anyhow::Result<()> { |
| 68 | + if duration > 0 { |
| 69 | + sleep(Duration::from_nanos(duration)).await; |
| 70 | + } |
| 71 | + Ok(()) |
| 72 | + } |
| 73 | +} |
0 commit comments