cycle_ptr 0.1.1

Smart pointers, with cycles
Documentation
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
//! Module for the strong pointer type.
use crate::object::{Object, ObjectIntf, ObjectPtr};
use crate::prelude::GcPtrEq;
use crate::{GcMemberPtr, Metadata};
use std::fmt;
use std::mem;
use std::ops::Deref;
use std::pin::Pin;
use std::ptr;

#[cfg(feature = "multi_thread")]
use super::SingleOrMultiThreadPtr;
#[cfg(all(feature = "multi_thread", feature = "weak_pointer"))]
use super::sync_weak;
#[cfg(feature = "weak_pointer")]
use super::weak::Weak;
#[cfg(feature = "multi_thread")]
use crate::object::{MTObjectIntf, MTObjectPtr};
#[cfg(feature = "multi_thread")]
use crate::sync::{GcMtMemberPtr, GcMtPtr};

#[cfg(feature = "weak_pointer")]
use crate::errors::Error;

/// A strong reference to an object.
///
/// This is for use in:
/// - global scope
/// - function scope
/// - members on objects that don't participate in the reachability-graph
pub struct GcPtr<T>
where
    T: 'static,
{
    /// Pointer to the actual [Object] holding on to `T` and the associated [ControlBlock][crate::generation::ControlBlock].
    #[cfg(not(feature = "multi_thread"))]
    pub(super) ptr: Pin<ObjectPtr<T>>,
    /// Pointer to the actual [Object]/[MTObject][crate::object::MTObject] holding on to `T` and the associated [ControlBlock][crate::generation::ControlBlock]/[MTControlBlock][crate::generation::MTControlBlock].
    #[cfg(feature = "multi_thread")]
    pub(super) ptr: SingleOrMultiThreadPtr<T>,
}

#[cfg(feature = "multi_thread")]
impl<T> From<GcMtPtr<T>> for GcPtr<T>
where
    T: 'static + Send + Sync,
{
    /// Turn a [GcMtPtr] into a [GcPtr].
    #[inline]
    fn from(sp: GcMtPtr<T>) -> GcPtr<T> {
        // We move sp.ptr without calling any Drop of sp,
        // so we can forego all the bookkeeping updates.
        //
        // SAFETY: this is safe because we will call the exact same code path upon drop.
        let sp_ptr = unsafe {
            let sp = mem::ManuallyDrop::new(sp);
            let mut new_ptr = mem::MaybeUninit::<Pin<MTObjectPtr<T>>>::zeroed();
            ptr::copy_nonoverlapping(&sp.ptr, new_ptr.as_mut_ptr(), 1);
            new_ptr.assume_init()
        };

        GcPtr { ptr: sp_ptr.into() }
    }
}

impl<T> Clone for GcPtr<T>
where
    T: 'static,
{
    #[inline]
    fn clone(&self) -> Self {
        let ptr = self.ptr.clone();
        #[cfg(not(feature = "multi_thread"))]
        ptr.get_control_block().refcount_inc();
        #[cfg(feature = "multi_thread")]
        match &ptr {
            SingleOrMultiThreadPtr::SingleThread(ptr) => ptr.get_control_block().refcount_inc(),
            SingleOrMultiThreadPtr::MultiThread(ptr) => ptr.get_control_block().refcount_inc(),
        };
        GcPtr { ptr }
    }
}

impl<T> Drop for GcPtr<T>
where
    T: 'static,
{
    #[inline]
    fn drop(&mut self) {
        #[cfg(not(feature = "multi_thread"))]
        self.ptr.get_control_block().refcount_dec();
        #[cfg(feature = "multi_thread")]
        match &self.ptr {
            SingleOrMultiThreadPtr::SingleThread(ptr) => ptr.get_control_block().refcount_dec(),
            SingleOrMultiThreadPtr::MultiThread(ptr) => ptr.get_control_block().refcount_dec(),
        };
    }
}

impl<T> Deref for GcPtr<T>
where
    T: 'static,
{
    type Target = T;

    #[inline]
    fn deref(&self) -> &T {
        #[cfg(not(feature = "multi_thread"))]
        return self.ptr.get_data();
        #[cfg(feature = "multi_thread")]
        return match &self.ptr {
            SingleOrMultiThreadPtr::SingleThread(ptr) => ptr.get_data(),
            SingleOrMultiThreadPtr::MultiThread(ptr) => ptr.get_data(),
        };
    }
}

impl<T> fmt::Debug for GcPtr<T>
where
    T: 'static + fmt::Debug,
{
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
        fmt::Debug::fmt(&**self, f)
    }
}

impl<T> GcPtr<T>
where
    T: 'static,
{
    /// Create a new [GcPtr].
    ///
    /// The factory function is given a [Metadata] that can be used to initialize [member pointers][GcMemberPtr].
    #[inline]
    pub fn new<Factory>(factory: Factory) -> GcPtr<T>
    where
        Factory: FnOnce(Metadata) -> T,
    {
        unsafe { GcPtr::new_from_raw(Object::new_ptr(1, factory, None)) }
    }

    /// Create a new [GcPtr].
    ///
    /// The factory function is given a [Metadata] that can be used to initialize [member pointers][GcMemberPtr].
    ///
    /// A [Weak] pointer is also provided to the factory function.
    /// Note that the [Weak] pointer can't be dereferenced until the object has actually been constructed.
    #[cfg(feature = "weak_pointer")]
    #[cfg_attr(docsrs, doc(cfg(feature = "weak_pointer")))]
    #[inline]
    pub fn new_cyclic<Factory>(factory: Factory) -> GcPtr<T>
    where
        Factory: FnOnce(Metadata, Weak<T>) -> T,
    {
        unsafe { GcPtr::new_from_raw(Object::new_cyclic_ptr(1, factory, None)) }
    }

    /// Downgrade to a [Weak] pointer.
    #[cfg(feature = "weak_pointer")]
    #[cfg_attr(docsrs, doc(cfg(feature = "weak_pointer")))]
    #[inline]
    pub fn downgrade(this: &Self) -> Weak<T> {
        Weak::new_ptr(this.ptr.clone())
    }

    /// Attempt to promote an unreferenced [ObjectPtr][crate::object::ObjectPtr]/[MTObjectPtr][crate::object::MTObjectPtr] to a strong pointer.
    ///
    /// # Errors
    ///
    /// Returns an [Error] if the [Object][crate::object::Object]/[MTObject][crate::object::MTObject] has [expired][crate::generation::ObjectState::Expired].
    #[cfg(all(not(feature = "multi_thread"), feature = "weak_pointer"))]
    pub(super) fn new_from_weak(ptr: &Pin<ObjectPtr<T>>) -> Result<Self, Error> {
        ptr.get_control_block()
            .try_refcount_inc()
            .map(|_| GcPtr { ptr: ptr.clone() })
    }

    /// Attempt to promote an unreferenced [ObjectPtr]/[MTObjectPtr] to a strong pointer.
    ///
    /// # Errors
    ///
    /// Returns an [Error] if the [Object]/[MTObject][crate::object::MTObject] has [expired][crate::generation::ObjectState::Expired].
    #[cfg(all(feature = "multi_thread", feature = "weak_pointer"))]
    pub(super) fn new_from_weak(ptr: &SingleOrMultiThreadPtr<T>) -> Result<Self, Error> {
        match ptr {
            SingleOrMultiThreadPtr::SingleThread(ptr) => {
                ptr.get_control_block().try_refcount_inc().map(|_| GcPtr {
                    ptr: SingleOrMultiThreadPtr::SingleThread(ptr.clone()),
                })
            }
            SingleOrMultiThreadPtr::MultiThread(ptr) => {
                ptr.get_control_block().try_refcount_inc().map(|_| GcPtr {
                    ptr: SingleOrMultiThreadPtr::MultiThread(ptr.clone()),
                })
            }
        }
    }

    /// Create a new pointer from raw [ObjectPtr].
    ///
    /// SAFETY: ObjectPtr must have 1 reference which will be adopted.
    #[cfg(not(feature = "multi_thread"))]
    #[inline]
    pub(crate) const unsafe fn new_from_raw(ptr: Pin<ObjectPtr<T>>) -> Self {
        GcPtr { ptr }
    }

    /// Create a new pointer from raw [ObjectPtr].
    ///
    /// SAFETY: ObjectPtr must have 1 reference which will be adopted.
    #[cfg(feature = "multi_thread")]
    #[inline]
    pub(crate) const unsafe fn new_from_raw(ptr: Pin<ObjectPtr<T>>) -> Self {
        GcPtr {
            ptr: SingleOrMultiThreadPtr::SingleThread(ptr),
        }
    }

    /// Create a new pointer from raw [ObjectPtr].
    ///
    /// SAFETY: MTObjectPtr must have 1 reference which will be adopted.
    #[cfg(feature = "multi_thread")]
    #[inline]
    pub(crate) const unsafe fn new_from_raw_mt(ptr: Pin<MTObjectPtr<T>>) -> Self {
        GcPtr {
            ptr: SingleOrMultiThreadPtr::MultiThread(ptr),
        }
    }

    /// Release the internal pointer, without decrementing the reference counter.
    #[cfg(not(feature = "multi_thread"))]
    #[inline]
    pub(super) unsafe fn release(this: Self) -> Pin<ObjectPtr<T>> {
        unsafe {
            let this = mem::ManuallyDrop::new(this);
            let mut new_ptr = mem::MaybeUninit::<Pin<ObjectPtr<T>>>::zeroed();
            ptr::copy_nonoverlapping(&this.ptr, new_ptr.as_mut_ptr(), 1);
            new_ptr.assume_init()
        }
    }

    /// Release the internal pointer, without decrementing the reference counter.
    #[cfg(feature = "multi_thread")]
    #[inline]
    pub(super) unsafe fn release(this: Self) -> SingleOrMultiThreadPtr<T> {
        unsafe {
            let this = mem::ManuallyDrop::new(this);
            let mut new_ptr = mem::MaybeUninit::<SingleOrMultiThreadPtr<T>>::zeroed();
            ptr::copy_nonoverlapping(&this.ptr, new_ptr.as_mut_ptr(), 1);
            new_ptr.assume_init()
        }
    }
}

impl<T> GcPtrEq<GcPtr<T>> for GcPtr<T>
where
    T: 'static,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &GcPtr<T>) -> bool {
        #[cfg(not(feature = "multi_thread"))]
        return ptr::eq(&*this.ptr, &*other.ptr);
        #[cfg(feature = "multi_thread")]
        return match (&this.ptr, &other.ptr) {
            (
                SingleOrMultiThreadPtr::SingleThread(this_ptr),
                SingleOrMultiThreadPtr::SingleThread(other_ptr),
            ) => ptr::eq(&**this_ptr, &**other_ptr),
            (SingleOrMultiThreadPtr::SingleThread(_), SingleOrMultiThreadPtr::MultiThread(_)) => {
                false
            }
            (SingleOrMultiThreadPtr::MultiThread(_), SingleOrMultiThreadPtr::SingleThread(_)) => {
                false
            }
            (
                SingleOrMultiThreadPtr::MultiThread(this_ptr),
                SingleOrMultiThreadPtr::MultiThread(other_ptr),
            ) => ptr::eq(&**this_ptr, &**other_ptr),
        };
    }
}

#[cfg(feature = "multi_thread")]
impl<T> GcPtrEq<GcMtPtr<T>> for GcPtr<T>
where
    T: 'static + Send + Sync,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &GcMtPtr<T>) -> bool {
        match &this.ptr {
            SingleOrMultiThreadPtr::MultiThread(this_ptr) => ptr::eq(&**this_ptr, &*other.ptr),
            _ => false,
        }
    }
}

impl<T> GcPtrEq<GcMemberPtr<T>> for GcPtr<T>
where
    T: 'static,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &GcMemberPtr<T>) -> bool {
        #[cfg(not(feature = "multi_thread"))]
        return ptr::eq(&*this.ptr, &*other.ptr);
        #[cfg(feature = "multi_thread")]
        return match (&this.ptr, &other.ptr) {
            (
                SingleOrMultiThreadPtr::SingleThread(this_ptr),
                SingleOrMultiThreadPtr::SingleThread(other_ptr),
            ) => ptr::eq(&**this_ptr, &**other_ptr),
            (SingleOrMultiThreadPtr::SingleThread(_), SingleOrMultiThreadPtr::MultiThread(_)) => {
                false
            }
            (SingleOrMultiThreadPtr::MultiThread(_), SingleOrMultiThreadPtr::SingleThread(_)) => {
                false
            }
            (
                SingleOrMultiThreadPtr::MultiThread(this_ptr),
                SingleOrMultiThreadPtr::MultiThread(other_ptr),
            ) => ptr::eq(&**this_ptr, &**other_ptr),
        };
    }
}

#[cfg(feature = "multi_thread")]
impl<T> GcPtrEq<GcMtMemberPtr<T>> for GcPtr<T>
where
    T: 'static + Send + Sync,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &GcMtMemberPtr<T>) -> bool {
        match &this.ptr {
            SingleOrMultiThreadPtr::MultiThread(this_ptr) => ptr::eq(&**this_ptr, &*other.ptr),
            _ => false,
        }
    }
}

#[cfg(feature = "weak_pointer")]
impl<T> GcPtrEq<Weak<T>> for GcPtr<T>
where
    T: 'static,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &Weak<T>) -> bool {
        #[cfg(not(feature = "multi_thread"))]
        return other
            .ptr
            .as_ref()
            .map(|other_ptr| ptr::eq(this.ptr.as_ref().get_ref(), other_ptr.as_ref().get_ref()))
            .unwrap_or(false);
        #[cfg(feature = "multi_thread")]
        return other
            .ptr
            .as_ref()
            .map(|other_ptr| match (&this.ptr, other_ptr) {
                (
                    SingleOrMultiThreadPtr::SingleThread(this_ptr),
                    SingleOrMultiThreadPtr::SingleThread(other_ptr),
                ) => ptr::eq(this_ptr.as_ref().get_ref(), other_ptr.as_ref().get_ref()),
                (
                    SingleOrMultiThreadPtr::SingleThread(_),
                    SingleOrMultiThreadPtr::MultiThread(_),
                ) => false,
                (
                    SingleOrMultiThreadPtr::MultiThread(_),
                    SingleOrMultiThreadPtr::SingleThread(_),
                ) => false,
                (
                    SingleOrMultiThreadPtr::MultiThread(this_ptr),
                    SingleOrMultiThreadPtr::MultiThread(other_ptr),
                ) => ptr::eq(this_ptr.as_ref().get_ref(), other_ptr.as_ref().get_ref()),
            })
            .unwrap_or(false);
    }
}

#[cfg(all(feature = "multi_thread", feature = "weak_pointer"))]
impl<T> GcPtrEq<sync_weak::Weak<T>> for GcPtr<T>
where
    T: 'static + Send + Sync,
{
    #[inline]
    fn ptr_eq(this: &Self, other: &sync_weak::Weak<T>) -> bool {
        other
            .ptr
            .as_ref()
            .map(|other_ptr| match &this.ptr {
                SingleOrMultiThreadPtr::SingleThread(_) => false,
                SingleOrMultiThreadPtr::MultiThread(this_ptr) => ptr::eq(&**this_ptr, &**other_ptr),
            })
            .unwrap_or(false)
    }
}

#[cfg(test)]
mod tests {
    use crate::GcPtr;
    use crate::prelude::GcPtrEq;
    use std::sync::{Arc, Mutex};

    #[derive(Debug)]
    struct Bla {
        n: Arc<Mutex<i32>>,
    }

    impl Bla {
        fn new(n: Arc<Mutex<i32>>) -> Bla {
            *n.lock().unwrap() += 1;
            Bla { n }
        }
    }

    impl Drop for Bla {
        fn drop(&mut self) {
            *self.n.lock().unwrap() -= 1;
        }
    }

    #[test]
    fn create_pointer() {
        let n = Arc::new(Mutex::new(0));
        let p = GcPtr::new(|_| Bla::new(n.clone()));
        assert_eq!(*n.lock().unwrap(), 1);

        drop(p);
        assert_eq!(*n.lock().unwrap(), 0);
    }

    #[test]
    fn clone_pointer() {
        let n = Arc::new(Mutex::new(0));
        let p = GcPtr::new(|_| Bla::new(n.clone()));
        let q = p.clone();
        assert_eq!(*n.lock().unwrap(), 1);

        drop(p);
        assert_eq!(*n.lock().unwrap(), 1);

        drop(q);
        assert_eq!(*n.lock().unwrap(), 0);
    }

    #[test]
    fn equality() {
        let n = Arc::new(Mutex::new(0));
        let p = GcPtr::new(|_| Bla::new(n.clone()));
        let q = p.clone();

        assert!(GcPtr::ptr_eq(&p, &q));
    }

    #[cfg(feature = "multi_thread")]
    #[test]
    #[cfg_attr(
        feature = "single_generation_mt",
        ignore = "In single-generation, any of the other test threads may be running the GC task, making it not run in this function, and thus fail the n=0 check at the end."
    )]
    fn from_sync_pointer() {
        let n = Arc::new(Mutex::new(0));
        let p = super::GcMtPtr::new(|_| Bla::new(n.clone()));
        let q = GcPtr::<Bla>::from(p);
        assert_eq!(*n.lock().unwrap(), 1);

        drop(q);
        assert_eq!(*n.lock().unwrap(), 0);
    }

    #[cfg(feature = "multi_thread")]
    #[test]
    fn equality_against_sync() {
        let n = Arc::new(Mutex::new(0));
        let p = super::GcMtPtr::new(|_| Bla::new(n.clone()));
        let q = GcPtr::from(p.clone());

        assert!(GcPtr::ptr_eq(&q, &p));
    }
}