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
//! This will run when is droped
//!
//! This will run in drop order, that means newest first
//!
//! ## features:
//!
//! - default = ["std"]
//! - std
//!
//! use `default-features=false` if you don't want to not have std

#![cfg_attr(not(feature = "std"), no_std)]

pub struct AfterDrop<F: FnOnce()>(Option<F>);

pub fn defer<F: FnOnce()>(func: F) -> AfterDrop<F> {
    AfterDrop::new(func)
}

impl<F: FnOnce()> AfterDrop<F> {
    #[must_use]
    pub fn new(func: F) -> Self {
        Self(Some(func))
    }
}

impl<F: FnOnce()> Drop for AfterDrop<F> {
    fn drop(&mut self) {
        self.0.take().unwrap()()
    }
}

impl<F: FnOnce()> From<F> for AfterDrop<F> {
    fn from(func: F) -> Self {
        Self::new(func)
    }
}

#[cfg(feature = "std")]
pub struct AfterDropBoxed(Option<Box<dyn FnOnce()>>);

#[cfg(feature = "std")]
impl AfterDropBoxed {
    #[must_use]
    pub fn new<F: FnOnce() + 'static>(func: F) -> Self {
        Self(Some(Box::new(func)))
    }
}

#[cfg(feature = "std")]
impl Drop for AfterDropBoxed {
    fn drop(&mut self) {
        self.0.take().unwrap()()
    }
}

#[cfg(feature = "std")]
impl<F: FnOnce() + 'static> From<F> for AfterDropBoxed {
    fn from(func: F) -> Self {
        Self::new(func)
    }
}