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
use futures::{Async, Future, Stream};

/// Wraps a stream or future and runs a callback when the stream/future ends or when `Finally` is
/// dropped.
pub struct Finally<F, D>
where
    D: FnOnce(),
{
    inner: Option<OnDrop<F, D>>,
}

struct OnDrop<F, D>
where
    D: FnOnce(),
{
    future: F,
    on_drop: Option<D>,
}

impl<F, D> Drop for OnDrop<F, D>
where
    D: FnOnce(),
{
    fn drop(&mut self) {
        unwrap!(self.on_drop.take())()
    }
}

impl<F, D> Finally<F, D>
where
    D: FnOnce(),
{
    pub fn new(future: F, on_drop: D) -> Finally<F, D> {
        Finally {
            inner: Some(OnDrop {
                future: future,
                on_drop: Some(on_drop),
            }),
        }
    }
}

impl<F, D> Future for Finally<F, D>
where
    F: Future,
    D: FnOnce(),
{
    type Item = F::Item;
    type Error = F::Error;

    fn poll(&mut self) -> Result<Async<F::Item>, F::Error> {
        let mut on_drop = unwrap!(self.inner.take());
        match on_drop.future.poll()? {
            Async::Ready(x) => Ok(Async::Ready(x)),
            Async::NotReady => {
                self.inner = Some(on_drop);
                Ok(Async::NotReady)
            },
        }
    }
}

impl<S, D> Stream for Finally<S, D>
where
    S: Stream,
    D: FnOnce(),
{
    type Item = S::Item;
    type Error = S::Error;

    fn poll(&mut self) -> Result<Async<Option<S::Item>>, S::Error> {
        let mut on_drop = unwrap!(self.inner.take());
        match on_drop.future.poll()? {
            Async::Ready(x) => Ok(Async::Ready(x)),
            Async::NotReady => {
                self.inner = Some(on_drop);
                Ok(Async::NotReady)
            },
        }
    }
}