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
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
/*!
Simple and fast dedicated thread drop.

# Example

```rust
use adrop::*;

struct Test {}

impl Drop for Test {
    fn drop(&mut self) {
        println!(
            "Dropping HasDrop! ThreadId: {:?}",
            std::thread::current().id()
        );
    }
}

println!("Main ThreadId: {:?}", std::thread::current().id());
adrop(Test {});
// Output:
// Main ThreadId: ThreadId(1)
// Dropping HasDrop! ThreadId: ThreadId(2)

// Or you can use `Adrop` wrapper to realize automatic `adrop`:
let _ = Adrop::new(Test {});
```
*/

use std::{
    mem::ManuallyDrop,
    ops::{Deref, DerefMut},
    sync::{
        mpsc::{channel, Sender},
        Mutex, Once,
    },
    thread::spawn,
};

type Trash = Box<dyn Send>;
type TrashSender = Sender<Trash>;

/// Pass the value to a dedicated thread for destruction.
///
/// # Examples
///
/// ```rust
/// use adrop::adrop;
///
/// struct Test {}
///
/// impl Drop for Test {
///     fn drop(&mut self) {
///         println!(
///             "Dropping HasDrop! ThreadId: {:?}",
///             std::thread::current().id()
///         );
///     }
/// }
///
/// println!("Main ThreadId: {:?}", std::thread::current().id());
/// adrop(Test {});
/// ```
///
/// Output:
///
/// ```text
/// Main ThreadId: ThreadId(1)
/// Dropping HasDrop! ThreadId: ThreadId(2)
/// ```
pub fn adrop<T: Send + 'static>(trash: T) {
    static mut TX: Option<Mutex<TrashSender>> = None;
    static TX_SET: Once = Once::new();
    TX_SET.call_once(|| {
        let (tx, rx) = channel();
        spawn(move || loop {
            let _ = rx.recv();
        });
        unsafe {
            TX = Some(Mutex::new(tx));
        }
    });
    unsafe {
        let _ = TX.as_ref().unwrap().lock().unwrap().send(Box::new(trash));
    }
}

/// `Adrop` wrapper can realize automatic `adrop`.
///
/// # Examples
///
/// ```rust
/// use adrop::Adrop;
///
/// struct Test {}
///
/// impl Drop for Test {
///     fn drop(&mut self) {
///         println!(
///             "Dropping HasDrop! ThreadId: {:?}",
///             std::thread::current().id()
///         );
///     }
/// }
///
/// println!("Main ThreadId: {:?}", std::thread::current().id());
/// let _ = Adrop::new(Test {});
/// ```
///
/// Output:
///
/// ```text
/// Main ThreadId: ThreadId(1)
/// Dropping HasDrop! ThreadId: ThreadId(2)
/// ```
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct Adrop<T: Send + 'static> {
    content: Option<ManuallyDrop<T>>,
}

impl<T: Send> Adrop<T> {
    /// Wrap a value to be realize automatic `adrop`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use adrop::Adrop;
    /// Adrop::new(String::from("Hello World!"));
    /// ```
    pub fn new(content: T) -> Adrop<T> {
        Adrop::<T> {
            content: Some(ManuallyDrop::new(content)),
        }
    }

    /// Extracts the value from the `Adrop` container.  
    /// This allows the value to be dropped again.
    /// # Examples
    ///
    /// ```rust
    /// use adrop::Adrop;
    /// let s = Adrop::new(String::from("Hello World!"));
    /// let _ = s.into_inner();
    /// ```
    pub fn into_inner(mut self) -> T {
        let content = unsafe { ManuallyDrop::take(self.content.as_mut().unwrap()) };
        self.content = None;
        content
    }
}

impl<T: Send> Deref for Adrop<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        self.content.as_ref().unwrap()
    }
}

impl<T: Send> DerefMut for Adrop<T> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        self.content.as_mut().unwrap()
    }
}

impl<T: Send> Drop for Adrop<T> {
    fn drop(&mut self) {
        if let Some(content) = self.content.as_mut() {
            unsafe {
                adrop(ManuallyDrop::take(content));
            }
        }
    }
}