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
use crate::Stopper;
use event_listener::EventListener;
use std::{
    future::{Future, IntoFuture},
    pin::Pin,
    task::{Context, Poll},
};

/// A future that awaits this Stopper being stopped
#[derive(Debug)]
pub struct Stopped {
    stopper: Stopper,
    event_listener: EventListener,
}

impl From<Stopper> for Stopped {
    fn from(value: Stopper) -> Self {
        value.into_future()
    }
}

impl From<Stopped> for Stopper {
    fn from(value: Stopped) -> Self {
        value.stopper
    }
}

impl Future for Stopped {
    type Output = ();

    fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
        let Self {
            stopper,
            event_listener,
        } = &mut *self;
        loop {
            if stopper.is_stopped() {
                return Poll::Ready(());
            }

            match Pin::new(&mut *event_listener).poll(cx) {
                Poll::Ready(()) => {
                    *event_listener = stopper.0.event.listen();
                    continue;
                }
                Poll::Pending => return Poll::Pending,
            };
        }
    }
}

impl IntoFuture for Stopper {
    type Output = ();
    type IntoFuture = Stopped;

    fn into_future(self) -> Self::IntoFuture {
        let event_listener = self.0.event.listen();
        Stopped {
            stopper: self,
            event_listener,
        }
    }
}