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
86
87
88
89
90
91
92
93
94
95
96
///! The code in this file was shamelessly stolen from
///! https://stackoverflow.com/questions/71541765/rust-async-drop
use std::time::Duration;

#[async_trait::async_trait]
pub trait AsyncDrop {
    async fn async_drop(&mut self);
}

#[derive(Default)]
#[allow(dead_code)]
pub struct AsyncDropper<T: AsyncDrop + Default + Send + 'static> {
    dropped: bool,
    timeout: Option<Duration>,
    inner: T,
}

impl<T: AsyncDrop + Default + Send + 'static> AsyncDropper<T> {
    pub fn new(inner: T) -> Self {
        Self {
            dropped: false,
            timeout: None,
            inner,
        }
    }

    pub fn with_timeout(timeout: Duration, inner: T) -> Self {
        Self {
            dropped: false,
            timeout: Some(timeout),
            inner,
        }
    }
}

#[cfg(all(not(feature = "tokio"), not(feature = "async-std")))]
impl<T: AsyncDrop + Default + Send + 'static> Drop for AsyncDropper<T> {
    fn drop(&mut self) {
        panic!("either 'async-std' or 'tokio' features must be enabled for the async-dropper crate")
    }
}

#[cfg(all(feature = "async-std", feature = "tokio"))]
impl<T: AsyncDrop + Default + Send + 'static> Drop for AsyncDropper<T> {}

#[cfg(all(feature = "tokio", not(feature = "async-std")))]
impl<T: AsyncDrop + Default + Send + 'static> Drop for AsyncDropper<T> {
    fn drop(&mut self) {
        if !self.dropped {
            let mut this = AsyncDropper::default();
            std::mem::swap(&mut this, self);
            this.dropped = true;

            // Create task
            let timeout = self.timeout.clone();
            let task = tokio::spawn(async move {
                this.inner.async_drop().await;
            });

            tokio::task::block_in_place(|| match timeout {
                Some(d) => {
                    let _ = futures::executor::block_on(tokio::time::timeout(d, task));
                }
                None => {
                    let _ = futures::executor::block_on(task);
                }
            });
        }
    }
}

#[cfg(all(feature = "async-std", not(feature = "tokio")))]
impl<T: AsyncDrop + Default + Send + 'static> Drop for AsyncDropper<T> {
    fn drop(&mut self) {
        if !self.dropped {
            let mut this = AsyncDropper::default();
            std::mem::swap(&mut this, self);
            this.dropped = true;

            // Create task
            let timeout = self.timeout.clone();
            let task = async_std::task::spawn(async move {
                this.inner.async_drop().await;
            });

            match timeout {
                Some(d) => {
                    let _ = futures::executor::block_on(async_std::future::timeout(d, task));
                }
                None => {
                    let _ = futures::executor::block_on(task);
                }
            };
        }
    }
}