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
use futures::Async;
use futures::Poll;
use futures::Stream;
use futures::future::Future;
use futures::sync::mpsc::unbounded;
use futures::sync::mpsc::UnboundedSender;
use futures::sync::mpsc::UnboundedReceiver;

pub fn shutdown_signal() -> (ShutdownSignal, ShutdownFuture) {
    let (tx, rx) = unbounded();
    (ShutdownSignal { tx: tx }, ShutdownFuture { rx: rx })
}

pub struct ShutdownSignal {
    tx: UnboundedSender<()>,
}

impl ShutdownSignal {
    pub fn shutdown(&self) {
        // ignore error, because receiver may be already removed
        drop(self.tx.send(()));
    }
}

impl Drop for ShutdownSignal {
    fn drop(&mut self) {
        self.shutdown();
    }
}

pub struct ShutdownFuture {
    rx: UnboundedReceiver<()>,
}

impl Future for ShutdownFuture {
    type Item = ();
    type Error = ();

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        match self.rx.poll() {
            Ok(Async::Ready(_)) => Err(()),
            Ok(Async::NotReady) => Ok(Async::NotReady),
            Err(_) => Err(()),
        }
    }
}