Skip to main content

harmos_storage/
execution.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10/* === Modules === */
11
12/* === Re-Exports === */
13
14/* === Imports === */
15
16// Standard Library Imports
17use std::future::Future;
18use std::pin::Pin;
19use std::time::Duration;
20
21// Third Party Imports
22use tokio::time::Instant;
23
24// Local Imports
25
26/* === Constants === */
27
28/* === Macros === */
29
30/* === Type Aliases === */
31
32pub type Sleep = Pin<Box<dyn Future<Output = ()> + Send>>;
33
34/* === Structs === */
35
36#[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
45/* === Enums === */
46
47/* === Traits === */
48
49/* === Implementations === */
50
51impl 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/* === Public Functions === */
73
74/* === Private Functions === */
75
76/* === Tests === */