harmos_storage/
execution.rs1use std::future::Future;
18use std::pin::Pin;
19use std::time::Duration;
20
21use tokio::time::Instant;
23
24pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send>>;
33
34#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub struct Elapsed;
38
39#[derive(Clone, Copy)]
40pub struct Execution {
41 now: fn() -> Instant,
42 sleep: fn(Duration) -> Sleep,
43}
44
45impl Execution {
52 pub const fn new(now: fn() -> Instant, sleep: fn(Duration) -> Sleep) -> Self {
53 Self { now, sleep }
54 }
55 pub fn now(self) -> Instant {
56 (self.now)()
57 }
58 pub fn sleep(self, duration: Duration) -> Sleep {
59 (self.sleep)(duration)
60 }
61 pub async fn timeout<F: Future>(self, duration: Duration, future: F) -> Result<F::Output, Elapsed> {
62 tokio::select! { biased; result = future => Ok(result), () = self.sleep(duration) => Err(Elapsed) }
63 }
64}
65
66impl Default for Execution {
67 fn default() -> Self {
68 Self::new(Instant::now, |duration| Box::pin(tokio::time::sleep(duration)))
69 }
70}
71
72