async_timer/
timed.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
//! Timed future

use core::future::Future;
use core::{fmt, task, time};
use core::pin::Pin;

use crate::timer::Timer;
use crate::timer::Platform as PlatformTimer;

struct State<'a, F, T> {
    timer: T,
    timeout: time::Duration,
    fut: Pin<&'a mut F>
}

#[must_use = "Timed does nothing unless polled"]
///Limiter on time to wait for underlying `Future`
///
///# Usage
///
///```rust, no_run
///async fn job() {
///}
///
///async fn do_job() {
///    let mut job = job();
///    let job = unsafe {
///        core::pin::Pin::new_unchecked(&mut job)
///    };
///    let work = unsafe {
///        async_timer::Timed::platform_new(job, core::time::Duration::from_secs(1))
///    };
///
///    match work.await {
///        Ok(_) => println!("I'm done!"),
///        //You can retry by polling `expired`
///        Err(expired) => println!("Job expired: {}", expired),
///    }
///}
///```
pub struct Timed<'a, F, T=PlatformTimer> {
    state: Option<State<'a, F, T>>,
}

impl<'a, F: Future> Timed<'a, F> {
    #[inline]
    ///Creates new instance using [Timer](../oneshot/type.Timer.html) alias.
    pub fn platform_new(fut: Pin<&'a mut F>, timeout: time::Duration) -> Self {
        Self::new(fut, timeout)
    }
}

impl<'a, F: Future, T: Timer> Timed<'a, F, T> {
    ///Creates new instance with specified timeout
    ///
    ///Unsafe version of `new` that doesn't require `Unpin`.
    ///
    ///Requires to specify `Timer` type (e.g. `Timed::<timer::Platform>::new()`)
    pub fn new(fut: Pin<&'a mut F>, timeout: time::Duration) -> Self {
        Self {
            state: Some(State {
                timer: T::new(timeout),
                timeout,
                fut,
            })
        }
    }
}

impl<'a, F: Future, T: Timer> Future for Timed<'a, F, T> {
    type Output = Result<F::Output, Expired<'a, F, T>>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> {
        let this = self.get_mut();

        if let Some(state) = this.state.as_mut() {
            match Future::poll(state.fut.as_mut(), ctx) {
                task::Poll::Pending => (),
                task::Poll::Ready(result) => return task::Poll::Ready(Ok(result)),
            }

            match Future::poll(Pin::new(&mut state.timer), ctx) {
                task::Poll::Pending => (),
                task::Poll::Ready(_) => return task::Poll::Ready(Err(Expired(this.state.take()))),
            }
        }

        task::Poll::Pending
    }
}

#[must_use = "Expire should be handled as error or to restart Timed"]
///Error when [Timed](struct.Timed.html) expires
///
///Implements `Future` that can be used to restart `Timed`
///Note, that `Timer` starts execution immediately after resolving this Future.
pub struct Expired<'a, F, T>(Option<State<'a, F, T>>);

impl<'a, F: Future, T: Timer> Future for Expired<'a, F, T> {
    type Output = Timed<'a, F, T>;

    fn poll(self: Pin<&mut Self>, ctx: &mut task::Context) -> task::Poll<Self::Output> {
        let this = self.get_mut();

        match this.0.take() {
            Some(mut state) => {
                state.timer.restart_ctx(state.timeout, ctx.waker());

                task::Poll::Ready(Timed {
                    state: Some(state)
                })
            },
            None => task::Poll::Pending,
        }
    }
}

#[cfg(feature = "std")]
impl<'a, F, T: Timer> crate::std::error::Error for Expired<'a, F, T> {}

impl<'a, F, T: Timer> fmt::Debug for Expired<'a, F, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self)
    }
}

impl<'a, F, T: Timer> fmt::Display for Expired<'a, F, T> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.0.as_ref() {
            None => write!(f, "Future is being re-tried."),
            Some(state) => match state.timeout.as_secs() {
                0 => write!(f, "Future expired in {} ms", state.timeout.as_millis()),
                secs => write!(f, "Future expired in {} seconds and {} ms", secs, state.timeout.subsec_millis()),
            },
        }
    }
}