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
use futures::{
    channel::oneshot::{Receiver, Sender},
    Stream,
};
use std::pin::Pin;

/// Stream wrapper that sends a message to a oneshot reciever upon being dropped.
#[derive(Debug)]
pub struct DropStream<T>
where
    T: Stream + ?Sized,
{
    pub stream: Pin<Box<T>>,
    pub tx: Option<Sender<()>>,
}

impl<T> DropStream<T>
where
    T: Stream + ?Sized,
{
    pub fn new(stream: Pin<Box<T>>) -> (DropStream<T>, Receiver<()>) {
        let (tx, rx) = futures::channel::oneshot::channel();

        let myself = Self {
            stream,
            tx: Some(tx),
        };

        return (myself, rx);
    }

    ///Given an existing `Stream` and `futures::channel::oneshot::Sender`, create a `DropStream` wrapper.
    pub fn from_existing_tx(stream: Pin<Box<T>>, tx: Sender<()>) -> DropStream<T> {
        let myself = Self {
            stream,
            tx: Some(tx),
        };

        return myself;
    }
}

impl<T> Drop for DropStream<T>
where
    T: Stream + ?Sized,
{
    fn drop(&mut self) {
        if let Some(tx) = self.tx.take() {
            let _ = tx.send(());
        };
    }
}

impl<T> Stream for DropStream<T>
where
    T: Stream + ?Sized,
{
    type Item = T::Item;

    fn poll_next(
        mut self: Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.stream.as_mut().poll_next(cx)
    }
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}