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

use pin_project::pin_project;

use crate::actor::Actor;
use crate::clock::{delay_for, Delay};
use crate::fut::ActorFuture;

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

pub fn new<F>(future: F, timeout: Duration) -> Timeout<F>
where
    F: ActorFuture,
{
    Timeout {
        fut: future,
        timeout: delay_for(timeout),
    }
}

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

    fn poll(
        self: Pin<&mut Self>,
        act: &mut F::Actor,
        ctx: &mut <F::Actor as Actor>::Context,
        task: &mut Context<'_>,
    ) -> Poll<Self::Output> {
        let this = self.project();

        if let Poll::Ready(_) = this.timeout.poll(task) {
            return Poll::Ready(Err(()));
        }

        this.fut.poll(act, ctx, task).map(Ok)
    }
}