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
// Copyright 2016 Amanieu d'Antras
//
// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
// http://opensource.org/licenses/MIT>, at your option. This file may not be
// copied, modified, or distributed except according to those terms.

#[cfg(feature = "alloc")]
use crate::alloc::boxed::Box;
#[cfg(feature = "alloc")]
use crate::alloc::rc::Rc;
#[cfg(feature = "alloc")]
use crate::alloc::sync::Arc;
use crate::UnsafeRef;
use core::mem;
use core::ops::Deref;

/// Trait representing an owned pointer type which can be converted to and from
/// a raw pointer.
///
/// This trait is automatically implemented for the standard `Box`, `Rc` and
/// `Arc` types. It is also implemented for the `UnsafeRef` pointer type
/// provided by this crate.
///
/// Rust reference types (`&T`) also implement `IntrusivePointer`. This is safe
/// because the lifetime of an intrusive collection is limited to that of the
/// pointer type. This means that a collection of `&'a T` cannot outlive any
/// objects that are inserted into the collection.
pub unsafe trait IntrusivePointer<T: ?Sized>: Deref<Target = T> + Sized {
    /// Consumes the owned pointer and returns a raw pointer to the owned object.
    ///
    /// The returned pointer must be the same as the one returned by `Deref`.
    fn into_raw(self) -> *const T {
        let ptr = self.deref() as *const _;
        mem::forget(self);
        ptr
    }

    /// Constructs an owned pointer from a raw pointer which was previously
    /// returned by `into_raw`.
    unsafe fn from_raw(ptr: *const T) -> Self;
}

unsafe impl<'a, T: ?Sized> IntrusivePointer<T> for &'a T {
    #[inline]
    fn into_raw(self) -> *const T {
        self
    }
    #[inline]
    unsafe fn from_raw(ptr: *const T) -> Self {
        &*ptr
    }
}

unsafe impl<T: ?Sized> IntrusivePointer<T> for UnsafeRef<T> {
    #[inline]
    fn into_raw(self) -> *const T {
        UnsafeRef::into_raw(self)
    }
    #[inline]
    unsafe fn from_raw(ptr: *const T) -> Self {
        UnsafeRef::from_raw(ptr)
    }
}

#[cfg(feature = "alloc")]
unsafe impl<T: ?Sized> IntrusivePointer<T> for Box<T> {
    #[inline]
    fn into_raw(self) -> *const T {
        Box::into_raw(self)
    }
    #[inline]
    unsafe fn from_raw(ptr: *const T) -> Self {
        Box::from_raw(ptr as *mut T)
    }
}

#[cfg(feature = "alloc")]
unsafe impl<T: ?Sized> IntrusivePointer<T> for Rc<T> {
    #[inline]
    fn into_raw(self) -> *const T {
        Rc::into_raw(self)
    }
    #[inline]
    unsafe fn from_raw(ptr: *const T) -> Rc<T> {
        Rc::from_raw(ptr)
    }
}

#[cfg(feature = "alloc")]
unsafe impl<T: ?Sized> IntrusivePointer<T> for Arc<T> {
    #[inline]
    fn into_raw(self) -> *const T {
        Arc::into_raw(self)
    }
    #[inline]
    unsafe fn from_raw(ptr: *const T) -> Arc<T> {
        Arc::from_raw(ptr)
    }
}

/// Creates an `IntrusivePointer` from a raw pointer
///
/// This method is only safe to call if the raw pointer is known to be
/// managed by the provided `IntrusivePointer` type.
pub(crate) unsafe fn clone_pointer_from_raw<P: IntrusivePointer<T> + Clone, T: ?Sized>(
    pointer: *const T,
) -> P {
    /// Guard which converts an `IntrusivePointer` back into its raw version
    /// when it gets dropped. This makes sure we also perform a full
    /// `from_raw` and `into_raw` round trip - even in the case of panics.
    struct PointerGuard<P: IntrusivePointer<T>, T: ?Sized> {
        pointer: Option<P>,
        _phantom: core::marker::PhantomData<T>,
    }

    impl<P: IntrusivePointer<T>, T: ?Sized> Drop for PointerGuard<P, T> {
        fn drop(&mut self) {
            // Prevent shared pointers from being released by converting them
            // back into the raw pointers
            let _ = self.pointer.take().unwrap().into_raw();
        }
    }

    let holder = PointerGuard {
        pointer: Some(P::from_raw(pointer)),
        _phantom: core::marker::PhantomData,
    };
    holder.pointer.as_ref().unwrap().clone()
}

#[cfg(test)]
mod tests {
    use super::IntrusivePointer;
    use std::boxed::Box;
    use std::fmt::Debug;
    use std::mem;
    use std::rc::Rc;
    use std::sync::Arc;

    #[test]
    fn test_box() {
        unsafe {
            let p = Box::new(1);
            let a: *const i32 = &*p;
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            let p2: Box<i32> = IntrusivePointer::from_raw(r);
            let a2: *const i32 = &*p2;
            assert_eq!(a, a2);
        }
    }

    #[test]
    fn test_rc() {
        unsafe {
            let p = Rc::new(1);
            let a: *const i32 = &*p;
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            let p2: Rc<i32> = IntrusivePointer::from_raw(r);
            let a2: *const i32 = &*p2;
            assert_eq!(a, a2);
        }
    }

    #[test]
    fn test_arc() {
        unsafe {
            let p = Arc::new(1);
            let a: *const i32 = &*p;
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            let p2: Arc<i32> = IntrusivePointer::from_raw(r);
            let a2: *const i32 = &*p2;
            assert_eq!(a, a2);
        }
    }

    #[test]
    fn test_box_unsized() {
        unsafe {
            let p = Box::new(1) as Box<dyn Debug>;
            let a: *const dyn Debug = &*p;
            let b: (usize, usize) = mem::transmute(a);
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            assert_eq!(b, mem::transmute(r));
            let p2: Box<dyn Debug> = IntrusivePointer::from_raw(r);
            let a2: *const dyn Debug = &*p2;
            assert_eq!(a, a2);
            assert_eq!(b, mem::transmute(a2));
        }
    }

    #[test]
    fn test_rc_unsized() {
        unsafe {
            let p = Rc::new(1) as Rc<dyn Debug>;
            let a: *const dyn Debug = &*p;
            let b: (usize, usize) = mem::transmute(a);
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            assert_eq!(b, mem::transmute(r));
            let p2: Rc<dyn Debug> = IntrusivePointer::from_raw(r);
            let a2: *const dyn Debug = &*p2;
            assert_eq!(a, a2);
            assert_eq!(b, mem::transmute(a2));
        }
    }

    #[test]
    fn test_arc_unsized() {
        unsafe {
            let p = Arc::new(1) as Arc<dyn Debug>;
            let a: *const dyn Debug = &*p;
            let b: (usize, usize) = mem::transmute(a);
            let r = IntrusivePointer::into_raw(p);
            assert_eq!(a, r);
            assert_eq!(b, mem::transmute(r));
            let p2: Arc<dyn Debug> = IntrusivePointer::from_raw(r);
            let a2: *const dyn Debug = &*p2;
            assert_eq!(a, a2);
            assert_eq!(b, mem::transmute(a2));
        }
    }

    #[test]
    fn clone_arc_from_raw() {
        use super::clone_pointer_from_raw;
        unsafe {
            let p = Arc::new(1);
            let raw = &*p as *const i32;
            let p2: Arc<i32> = clone_pointer_from_raw(raw);
            assert_eq!(2, Arc::strong_count(&p2));
        }
    }

    #[test]
    fn clone_rc_from_raw() {
        use super::clone_pointer_from_raw;
        unsafe {
            let p = Rc::new(1);
            let raw = &*p as *const i32;
            let p2: Rc<i32> = clone_pointer_from_raw(raw);
            assert_eq!(2, Rc::strong_count(&p2));
        }
    }
}