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
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
#[cfg(feature = "nightly-features")]
use std::{marker::Unsize, ops::CoerceUnsized};

use crate::collector::{InternalGcRef, COLLECTOR};
use crate::marker::{GcDeref, GcDrop, GcSafe};
use crate::{Finalize, Scan, Scanner, ToScan};

use std::any::{Any, TypeId};
use std::cmp::Ordering;
use std::fmt;
use std::fmt::{Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;

/// A `Gc`, but with the ability to `Deref` to its contents!
///
/// This comes with the requirement that your data implement `GcDeref`, which can be limiting. See
/// `GcDeref` documentation for details.
pub struct DerefGc<T: Scan + GcDeref + ?Sized> {
    backing_handle: InternalGcRef,
    direct_ptr: *const T,
}

impl<T: Scan + GcDeref + ?Sized> DerefGc<T> {
    /// Create a new `DerefGc` containing the given data.
    /// `T: GcDrop` in order to create a `Gc<T>` with this method.
    /// If your `T` is not `GcDrop`, consider `new_with_finalizer`.
    ///
    /// When this data is garbage collected, its `drop` implementation will be run.
    ///
    /// It is possible for this data not to be collected before the program terminates, or for
    /// the program to terminate before the background thread runs its destructor. So be careful
    /// when relying on this guarantee.
    pub fn new(v: T) -> Self
    where
        T: Sized + GcDrop,
    {
        let (handle, ptr) = COLLECTOR.track_with_drop(v);
        Self {
            backing_handle: handle,
            direct_ptr: ptr,
        }
    }

    /// Create a new `DerefGc` containing the given data. (But specifying not to run its destructor.)
    /// This is useful because `T: GcDrop` is no longer necessary!
    ///
    /// When this data is garbage collected, its `drop` implementation will NOT be run.
    /// Be careful using this method! It can lead to memory leaks!
    pub fn new_no_drop(v: T) -> Self
    where
        T: Sized,
    {
        let (handle, ptr) = COLLECTOR.track_with_no_drop(v);
        Self {
            backing_handle: handle,
            direct_ptr: ptr,
        }
    }

    /// Create a new `DerefGc` containing the given data. (But specifying to call `finalize` on it
    /// instead of running its destructor.)
    /// This is useful because `T: GcDrop` is no longer necessary!
    ///
    /// As long as `finalize` does what you think it does, this is probably what you want for
    /// non-`'static`/non-`GcDrop` data!
    ///
    /// It is possible for this data not to be collected before the program terminates, or for
    /// the program to terminate before the background thread runs `finalize`. So be careful!
    pub fn new_with_finalizer(v: T) -> Self
    where
        T: Sized + Finalize,
    {
        let (handle, ptr) = COLLECTOR.track_with_finalization(v);
        Self {
            backing_handle: handle,
            direct_ptr: ptr,
        }
    }

    /// Create a new `DerefGc` using the given `Box<T>`.
    ///
    /// This function does not allocate anything - rather, it uses the `Box<T>` and releases its
    /// memory appropriately. This is useful since it removes the requirement for types to be
    /// sized.
    pub fn from_box(v: Box<T>) -> Self
    where
        T: ToScan + GcDrop,
    {
        let (handle, ptr) = COLLECTOR.track_boxed_value(v);
        Self {
            backing_handle: handle,
            direct_ptr: ptr,
        }
    }
}

#[allow(clippy::use_self)]
impl<T: Scan + GcDeref + ?Sized> DerefGc<T> {
    /// Attempt to `downcast` this `DerefGc<T>` to a `DerefGc<S>`
    ///
    /// For implementation reasons this returns a new `DerefGc<T>` on success
    /// On failure (if there was not an `S` in the `DerefGc<T>`) then `None` is returned
    #[must_use]
    pub fn downcast<S>(&self) -> Option<DerefGc<S>>
    where
        T: Any + 'static,
        S: Scan + GcDeref + Any + 'static,
    {
        let ptr: &T = self.deref();

        if ptr.type_id() == TypeId::of::<S>() {
            let new_handle = COLLECTOR.clone_handle(&self.backing_handle);

            Some(DerefGc {
                backing_handle: new_handle,
                direct_ptr: self.direct_ptr as *const S,
            })
        } else {
            None
        }
    }
}

unsafe impl<T: Scan + GcDeref + ?Sized> GcSafe for DerefGc<T> {}
// unsafe impl<T: Scan + GcDeref + ?Sized> !GcDrop for DerefGc<T> {}
unsafe impl<T: Scan + GcDeref + Send + Sync + ?Sized> GcDeref for DerefGc<T> {}

// Same bounds as Arc<T>
unsafe impl<T: Scan + GcDeref + ?Sized> Sync for DerefGc<T> where T: Sync + Send {}
unsafe impl<T: Scan + GcDeref + ?Sized> Send for DerefGc<T> where T: Sync + Send {}
// Since we can clone DerefGc<T>, being able to send a DerefGc<T> implies possible sharing between threads
// (Thus for DerefGc<T> to be send, T must be Send and Sync)

// This is a fundamental implementation, since it's how GcInternalHandles make it into the Scanner
// Safety: The implementation is built around this, so it's by definition safe
unsafe impl<T: Scan + GcDeref + ?Sized> Scan for DerefGc<T> {
    #[allow(clippy::inline_always)]
    #[inline(always)]
    fn scan(&self, scanner: &mut Scanner<'_>) {
        scanner.add_internal_handle(self.backing_handle.clone());
    }
}

impl<T: Scan + GcDeref + ?Sized> Clone for DerefGc<T> {
    fn clone(&self) -> Self {
        let new_handle = COLLECTOR.clone_handle(&self.backing_handle);

        Self {
            backing_handle: new_handle,
            direct_ptr: self.direct_ptr,
        }
    }
}

impl<T: Scan + GcDeref + ?Sized> Deref for DerefGc<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        unsafe { &*self.direct_ptr }
    }
}

impl<T: Scan + GcDeref + ?Sized> Drop for DerefGc<T> {
    fn drop(&mut self) {
        self.backing_handle.invalidate()
    }
}

unsafe impl<T: Scan + GcDeref + ?Sized> Finalize for DerefGc<T> {
    unsafe fn finalize(&mut self) {
        self.backing_handle.invalidate();
    }
}

#[cfg(feature = "nightly-features")]
impl<T, U> CoerceUnsized<DerefGc<U>> for DerefGc<T>
where
    T: Scan + GcDeref + ?Sized + Unsize<U>,
    U: Scan + GcDeref + ?Sized,
{
}

impl<T: Scan + GcDeref + ?Sized> Debug for DerefGc<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_struct("DerefGc")
            .field("backing_handle", &"<SNIP>")
            .field("direct_ptr", &self.direct_ptr)
            .finish()
    }
}

impl<T: Scan + GcDeref + ?Sized> Default for DerefGc<T>
where
    T: Default + GcDrop,
{
    #[must_use]
    fn default() -> Self {
        let v = T::default();
        Self::new(v)
    }
}

impl<T: Scan + GcDeref + ?Sized> Display for DerefGc<T>
where
    T: Display,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        self.deref().fmt(f)
    }
}

impl<T: Scan + GcDeref + ?Sized> fmt::Pointer for DerefGc<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        fmt::Pointer::fmt(&self.direct_ptr, f)
    }
}

impl<T: Scan + GcDeref + ?Sized> Eq for DerefGc<T> where T: Eq {}

impl<T: Scan + GcDeref + ?Sized> Hash for DerefGc<T>
where
    T: Hash,
{
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.deref().hash(state)
    }
}

impl<T: Scan + GcDeref + ?Sized> Ord for DerefGc<T>
where
    T: Ord,
{
    #[must_use]
    fn cmp(&self, other: &Self) -> Ordering {
        (self.deref()).cmp(other.deref())
    }
}

#[allow(clippy::partialeq_ne_impl)]
impl<T: Scan + GcDeref + ?Sized> PartialEq for DerefGc<T>
where
    T: PartialEq,
{
    #[must_use]
    fn eq(&self, other: &Self) -> bool {
        (self.deref()).eq(other.deref())
    }

    #[must_use]
    fn ne(&self, other: &Self) -> bool {
        (self.deref()).ne(other.deref())
    }
}

impl<T: Scan + GcDeref + ?Sized> PartialOrd for DerefGc<T>
where
    T: PartialOrd,
{
    #[must_use]
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        (self.deref()).partial_cmp(other.deref())
    }

    #[must_use]
    fn lt(&self, other: &Self) -> bool {
        (self.deref()).lt(other.deref())
    }

    #[must_use]
    fn le(&self, other: &Self) -> bool {
        (self.deref()).le(other.deref())
    }

    #[must_use]
    fn gt(&self, other: &Self) -> bool {
        (self.deref()).gt(other.deref())
    }

    #[must_use]
    fn ge(&self, other: &Self) -> bool {
        (self.deref()).ge(other.deref())
    }
}