stackbox/
ptr.rs

1//! Module that attemps to define a `Unique<T>` pointer:
2//!
3//!  - non-null, well-aligned & read-write dereferenceable,
4//!    (for some _valid_ instance; wrap the `T` in a `MaybeUninit` to loosen
5//!    that validity invariant)
6//!  - unaliased,
7//!  - covariant.
8//!
9//! When `Box` is available, `MD<Box<T>>` happens to satisfy all these
10//! requirements, but for the dereferenceable one.
11//!
12//! Otherwise, `ptr::NonNull<T>` is the maximal covariant wrapper available
13//! to stable Rust… đŸ˜©
14
15#[allow(unused_imports)]
16pub(crate) use ::core::ptr::*;
17
18pub(crate) use __::Unique;
19
20#[cfg(feature = "alloc")]
21pub(crate) mod __ {
22    use ::alloc::boxed::Box;
23    use ::core::{mem::ManuallyDrop as MD, ptr};
24
25    #[repr(transparent)]
26    pub(crate) struct Unique<T: ?Sized>(MD<Box<T>>);
27
28    impl<T: ?Sized> Unique<T> {
29        #[inline]
30        pub(crate) unsafe fn from_raw(ptr: *mut T) -> Unique<T> {
31            Self(MD::new(Box::from_raw(ptr)))
32        }
33
34        #[inline]
35        pub(crate) fn into_raw_nonnull(self: Unique<T>) -> ptr::NonNull<T> {
36            Box::leak(MD::into_inner(self.0)).into()
37        }
38
39        #[inline]
40        pub(crate) unsafe fn drop_in_place(this: &'_ mut Unique<T>) {
41            ptr::drop_in_place::<T>(&mut **this)
42        }
43    }
44
45    impl<T: ?Sized> ::core::ops::Deref for Unique<T> {
46        type Target = T;
47
48        #[inline]
49        fn deref(self: &'_ Unique<T>) -> &'_ T {
50            &**self.0
51        }
52    }
53
54    impl<T: ?Sized> ::core::ops::DerefMut for Unique<T> {
55        #[inline]
56        fn deref_mut(self: &'_ mut Unique<T>) -> &'_ mut T {
57            &mut **self.0
58        }
59    }
60}
61
62#[cfg(not(feature = "alloc"))]
63pub(crate) mod __ {
64    use ::core::ptr;
65
66    #[repr(transparent)]
67    pub(crate) struct Unique<T: ?Sized>(ptr::NonNull<T>);
68
69    unsafe impl<T: Send + ?Sized> Send for Unique<T> {}
70    unsafe impl<T: Sync + ?Sized> Sync for Unique<T> {}
71
72    impl<T: ?Sized> Unique<T> {
73        #[inline]
74        pub(crate) unsafe fn from_raw(ptr: *mut T) -> Unique<T> {
75            Self(ptr::NonNull::new_unchecked(ptr))
76        }
77
78        #[inline]
79        pub(crate) fn into_raw_nonnull(self: Unique<T>) -> ptr::NonNull<T> {
80            self.0
81        }
82
83        #[inline]
84        pub(crate) unsafe fn drop_in_place(this: &'_ mut Unique<T>) {
85            ptr::drop_in_place(this.0.as_ptr())
86        }
87    }
88
89    impl<T: ?Sized> ::core::ops::Deref for Unique<T> {
90        type Target = T;
91
92        #[inline]
93        fn deref(self: &'_ Unique<T>) -> &'_ T {
94            unsafe { self.0.as_ref() }
95        }
96    }
97
98    impl<T: ?Sized> ::core::ops::DerefMut for Unique<T> {
99        #[inline]
100        fn deref_mut(self: &'_ mut Unique<T>) -> &'_ mut T {
101            unsafe { self.0.as_mut() }
102        }
103    }
104}