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
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::{self, Sleep};
use crate::fut::ActorStream;

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 = "streams do nothing unless polled"]
    pub struct StreamTimeout<S>
    where
        S: ActorStream,
    {
        #[pin]
        stream: S,
        dur: Duration,
        #[pin]
        timeout: Option<Sleep>,
    }
}

pub fn new<S>(stream: S, timeout: Duration) -> StreamTimeout<S>
where
    S: ActorStream,
{
    StreamTimeout {
        stream,
        dur: timeout,
        timeout: None,
    }
}

impl<S> ActorStream for StreamTimeout<S>
where
    S: ActorStream,
{
    type Item = Result<S::Item, ()>;
    type Actor = S::Actor;

    fn poll_next(
        self: Pin<&mut Self>,
        act: &mut S::Actor,
        ctx: &mut <S::Actor as Actor>::Context,
        task: &mut Context<'_>,
    ) -> Poll<Option<Result<S::Item, ()>>> {
        let mut this = self.project();

        match this.stream.poll_next(act, ctx, task) {
            Poll::Ready(Some(res)) => {
                this.timeout.set(None);
                return Poll::Ready(Some(Ok(res)));
            }
            Poll::Ready(None) => return Poll::Ready(None),
            Poll::Pending => (),
        }

        if this.timeout.is_none() {
            this.timeout.set(Some(clock::sleep(*this.dur)));
        }

        // check timeout
        if this
            .timeout
            .as_mut()
            .as_pin_mut()
            .unwrap()
            .poll(task)
            .is_pending()
        {
            return Poll::Pending;
        }
        this.timeout.set(None);

        Poll::Ready(Some(Err(())))
    }
}