core/pin/unsafe_pinned.rs
1use crate::cell::UnsafeCell;
2use crate::marker::{PointerLike, Unpin};
3use crate::ops::{CoerceUnsized, DispatchFromDyn};
4use crate::pin::Pin;
5use crate::{fmt, ptr};
6
7/// This type provides a way to entirely opt-out of typical aliasing rules;
8/// specifically, `&mut UnsafePinned<T>` is not guaranteed to be a unique pointer.
9/// This also subsumes the effects of `UnsafeCell`, i.e., `&UnsafePinned<T>` may point to data
10/// that is being mutated.
11///
12/// However, even if you define your type like `pub struct Wrapper(UnsafePinned<...>)`, it is still
13/// very risky to have an `&mut Wrapper` that aliases anything else. Many functions that work
14/// generically on `&mut T` assume that the memory that stores `T` is uniquely owned (such as
15/// `mem::swap`). In other words, while having aliasing with `&mut Wrapper` is not immediate
16/// Undefined Behavior, it is still unsound to expose such a mutable reference to code you do not
17/// control! Techniques such as pinning via [`Pin`] are needed to ensure soundness.
18///
19/// Similar to [`UnsafeCell`](crate::cell::UnsafeCell), `UnsafePinned` will not usually show up in
20/// the public API of a library. It is an internal implementation detail of libraries that need to
21/// support aliasing mutable references.
22///
23/// This type blocks niches the same way `UnsafeCell` does.
24#[lang = "unsafe_pinned"]
25#[repr(transparent)]
26#[unstable(feature = "unsafe_pinned", issue = "125735")]
27pub struct UnsafePinned<T: ?Sized> {
28 value: UnsafeCell<T>,
29}
30
31// Override the manual `!Sync` in `UnsafeCell`.
32#[unstable(feature = "unsafe_pinned", issue = "125735")]
33unsafe impl<T: ?Sized + Sync> Sync for UnsafePinned<T> {}
34
35/// When this type is used, that almost certainly means safe APIs need to use pinning to avoid the
36/// aliases from becoming invalidated. Therefore let's mark this as `!Unpin`. You can always opt
37/// back in to `Unpin` with an `impl` block, provided your API is still sound while unpinned.
38#[unstable(feature = "unsafe_pinned", issue = "125735")]
39impl<T: ?Sized> !Unpin for UnsafePinned<T> {}
40
41// `Send` and `Sync` are inherited from `T`. This is similar to `SyncUnsafeCell`, since
42// we eventually concluded that `UnsafeCell` implicitly making things `!Sync` is sometimes
43// unergonomic. A type that needs to be `!Send`/`!Sync` should really have an explicit
44// opt-out itself, e.g. via an `PhantomData<*mut T>` or (one day) via `impl !Send`/`impl !Sync`.
45
46impl<T> UnsafePinned<T> {
47 /// Constructs a new instance of `UnsafePinned` which will wrap the specified value.
48 ///
49 /// All access to the inner value through `&UnsafePinned<T>` or `&mut UnsafePinned<T>` or
50 /// `Pin<&mut UnsafePinned<T>>` requires `unsafe` code.
51 #[inline(always)]
52 #[must_use]
53 #[unstable(feature = "unsafe_pinned", issue = "125735")]
54 pub const fn new(value: T) -> Self {
55 UnsafePinned { value: UnsafeCell::new(value) }
56 }
57
58 /// Unwraps the value, consuming this `UnsafePinned`.
59 #[inline(always)]
60 #[must_use]
61 #[unstable(feature = "unsafe_pinned", issue = "125735")]
62 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
63 pub const fn into_inner(self) -> T {
64 self.value.into_inner()
65 }
66}
67
68impl<T: ?Sized> UnsafePinned<T> {
69 /// Get read-write access to the contents of a pinned `UnsafePinned`.
70 #[inline(always)]
71 #[must_use]
72 #[unstable(feature = "unsafe_pinned", issue = "125735")]
73 pub const fn get_mut_pinned(self: Pin<&mut Self>) -> *mut T {
74 // SAFETY: we're not using `get_unchecked_mut` to unpin anything
75 unsafe { self.get_unchecked_mut() }.get_mut_unchecked()
76 }
77
78 /// Get read-write access to the contents of an `UnsafePinned`.
79 ///
80 /// You should usually be using `get_mut_pinned` instead to explicitly track the fact that this
81 /// memory is "pinned" due to there being aliases.
82 #[inline(always)]
83 #[must_use]
84 #[unstable(feature = "unsafe_pinned", issue = "125735")]
85 pub const fn get_mut_unchecked(&mut self) -> *mut T {
86 ptr::from_mut(self) as *mut T
87 }
88
89 /// Get read-only access to the contents of a shared `UnsafePinned`.
90 ///
91 /// Note that `&UnsafePinned<T>` is read-only if `&T` is read-only. This means that if there is
92 /// mutation of the `T`, future reads from the `*const T` returned here are UB! Use
93 /// [`UnsafeCell`] if you also need interior mutability.
94 ///
95 /// [`UnsafeCell`]: crate::cell::UnsafeCell
96 ///
97 /// ```rust,no_run
98 /// #![feature(unsafe_pinned)]
99 /// use std::pin::UnsafePinned;
100 ///
101 /// unsafe {
102 /// let mut x = UnsafePinned::new(0);
103 /// let ptr = x.get(); // read-only pointer, assumes immutability
104 /// x.get_mut_unchecked().write(1);
105 /// ptr.read(); // UB!
106 /// }
107 /// ```
108 #[inline(always)]
109 #[must_use]
110 #[unstable(feature = "unsafe_pinned", issue = "125735")]
111 pub const fn get(&self) -> *const T {
112 ptr::from_ref(self) as *const T
113 }
114
115 /// Gets an immutable pointer to the wrapped value.
116 ///
117 /// The difference from [`get`] is that this function accepts a raw pointer, which is useful to
118 /// avoid the creation of temporary references.
119 ///
120 /// [`get`]: UnsafePinned::get
121 #[inline(always)]
122 #[must_use]
123 #[unstable(feature = "unsafe_pinned", issue = "125735")]
124 pub const fn raw_get(this: *const Self) -> *const T {
125 this as *const T
126 }
127
128 /// Gets a mutable pointer to the wrapped value.
129 ///
130 /// The difference from [`get_mut_pinned`] and [`get_mut_unchecked`] is that this function
131 /// accepts a raw pointer, which is useful to avoid the creation of temporary references.
132 ///
133 /// [`get_mut_pinned`]: UnsafePinned::get_mut_pinned
134 /// [`get_mut_unchecked`]: UnsafePinned::get_mut_unchecked
135 #[inline(always)]
136 #[must_use]
137 #[unstable(feature = "unsafe_pinned", issue = "125735")]
138 pub const fn raw_get_mut(this: *mut Self) -> *mut T {
139 this as *mut T
140 }
141}
142
143#[unstable(feature = "unsafe_pinned", issue = "125735")]
144impl<T: Default> Default for UnsafePinned<T> {
145 /// Creates an `UnsafePinned`, with the `Default` value for T.
146 fn default() -> Self {
147 UnsafePinned::new(T::default())
148 }
149}
150
151#[unstable(feature = "unsafe_pinned", issue = "125735")]
152impl<T> From<T> for UnsafePinned<T> {
153 /// Creates a new `UnsafePinned<T>` containing the given value.
154 fn from(value: T) -> Self {
155 UnsafePinned::new(value)
156 }
157}
158
159#[unstable(feature = "unsafe_pinned", issue = "125735")]
160impl<T: ?Sized> fmt::Debug for UnsafePinned<T> {
161 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
162 f.debug_struct("UnsafePinned").finish_non_exhaustive()
163 }
164}
165
166#[unstable(feature = "coerce_unsized", issue = "18598")]
167// #[unstable(feature = "unsafe_pinned", issue = "125735")]
168impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafePinned<U>> for UnsafePinned<T> {}
169
170// Allow types that wrap `UnsafePinned` to also implement `DispatchFromDyn`
171// and become dyn-compatible method receivers.
172// Note that currently `UnsafePinned` itself cannot be a method receiver
173// because it does not implement Deref.
174// In other words:
175// `self: UnsafePinned<&Self>` won't work
176// `self: UnsafePinned<Self>` becomes possible
177// FIXME(unsafe_pinned) this logic is copied from UnsafeCell, is it still sound?
178#[unstable(feature = "dispatch_from_dyn", issue = "none")]
179// #[unstable(feature = "unsafe_pinned", issue = "125735")]
180impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafePinned<U>> for UnsafePinned<T> {}
181
182#[unstable(feature = "pointer_like_trait", issue = "none")]
183// #[unstable(feature = "unsafe_pinned", issue = "125735")]
184impl<T: PointerLike> PointerLike for UnsafePinned<T> {}
185
186// FIXME(unsafe_pinned): impl PinCoerceUnsized for UnsafePinned<T>?