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
use std::future::Future;
use std::pin::Pin;
use std::task::{Context, Poll};
use std::time::Duration;

use pin_project_lite::pin_project;

use crate::actor::Actor;
use crate::clock::{sleep, Sleep};
use crate::fut::ActorFuture;

pin_project! {
    /// Future for the `timeout` combinator, interrupts computations if it takes
    /// more than `timeout`.
    ///
    /// This is created by the `ActorFuture::timeout()` method.
    #[derive(Debug)]
    #[must_use = "futures do nothing unless polled"]
    pub struct Timeout<F>{
        #[pin]
        fut: F,
        #[pin]
        timeout: Sleep,
    }
}

impl<F> Timeout<F> {
    pub(super) fn new(future: F, timeout: Duration) -> Self {
        Self {
            fut: future,
            timeout: sleep(timeout),
        }
    }
}

impl<F, A> ActorFuture<A> for Timeout<F>
where
    F: ActorFuture<A>,
    A: Actor,
{
    type Output = Result<F::Output, ()>;

    fn poll(
        self: Pin<&mut Self>,
        act: &mut A,
        ctx: &mut A::Context,
        task: &mut Context<'_>,
    ) -> Poll<Self::Output> {
        let this = self.project();
        match this.fut.poll(act, ctx, task) {
            Poll::Ready(res) => Poll::Ready(Ok(res)),
            Poll::Pending => this.timeout.poll(task).map(Err),
        }
    }
}