core/pin/unsafe_pinned.rs
1use crate::cell::UnsafeCell;
2use crate::marker::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 #[ferrocene::prevalidated]
52 #[inline(always)]
53 #[must_use]
54 #[unstable(feature = "unsafe_pinned", issue = "125735")]
55 pub const fn new(value: T) -> Self {
56 UnsafePinned { value: UnsafeCell::new(value) }
57 }
58
59 /// Unwraps the value, consuming this `UnsafePinned`.
60 #[inline(always)]
61 #[must_use]
62 #[unstable(feature = "unsafe_pinned", issue = "125735")]
63 #[rustc_allow_const_fn_unstable(const_precise_live_drops)]
64 pub const fn into_inner(self) -> T {
65 self.value.into_inner()
66 }
67}
68
69impl<T: ?Sized> UnsafePinned<T> {
70 /// Get read-write access to the contents of a pinned `UnsafePinned`.
71 #[inline(always)]
72 #[must_use]
73 #[unstable(feature = "unsafe_pinned", issue = "125735")]
74 pub const fn get_mut_pinned(self: Pin<&mut Self>) -> *mut T {
75 // SAFETY: we're not using `get_unchecked_mut` to unpin anything
76 unsafe { self.get_unchecked_mut() }.get_mut_unchecked()
77 }
78
79 /// Get read-write access to the contents of an `UnsafePinned`.
80 ///
81 /// You should usually be using `get_mut_pinned` instead to explicitly track the fact that this
82 /// memory is "pinned" due to there being aliases.
83 #[inline(always)]
84 #[must_use]
85 #[unstable(feature = "unsafe_pinned", issue = "125735")]
86 pub const fn get_mut_unchecked(&mut self) -> *mut T {
87 ptr::from_mut(self) as *mut T
88 }
89
90 /// Get mutable access to the contents of a shared `UnsafePinned`.
91 ///
92 /// This can be cast to a pointer of any kind. When creating references, you must uphold the
93 /// aliasing rules; see [`UnsafeCell`] for more discussion and caveats.
94 ///
95 /// [`UnsafeCell`]: crate::cell::UnsafeCell#aliasing-rules
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();
104 /// x.get_mut_unchecked().write(1);
105 /// assert_eq!(ptr.read(), 1);
106 /// }
107 /// ```
108 #[ferrocene::prevalidated]
109 #[inline(always)]
110 #[must_use]
111 #[unstable(feature = "unsafe_pinned", issue = "125735")]
112 pub const fn get(&self) -> *mut T {
113 self.value.get()
114 }
115
116 /// Gets an immutable pointer to the wrapped value.
117 ///
118 /// The difference from [`get`] is that this function accepts a raw pointer, which is useful to
119 /// avoid the creation of temporary references.
120 ///
121 /// [`get`]: UnsafePinned::get
122 #[inline(always)]
123 #[must_use]
124 #[unstable(feature = "unsafe_pinned", issue = "125735")]
125 pub const fn raw_get(this: *const Self) -> *mut T {
126 this as *const T as *mut T
127 }
128
129 /// Gets a mutable pointer to the wrapped value.
130 ///
131 /// The difference from [`get_mut_pinned`] and [`get_mut_unchecked`] is that this function
132 /// accepts a raw pointer, which is useful to avoid the creation of temporary references.
133 ///
134 /// [`get_mut_pinned`]: UnsafePinned::get_mut_pinned
135 /// [`get_mut_unchecked`]: UnsafePinned::get_mut_unchecked
136 #[inline(always)]
137 #[must_use]
138 #[unstable(feature = "unsafe_pinned", issue = "125735")]
139 pub const fn raw_get_mut(this: *mut Self) -> *mut T {
140 this as *mut T
141 }
142}
143
144#[unstable(feature = "unsafe_pinned", issue = "125735")]
145impl<T: Default> Default for UnsafePinned<T> {
146 /// Creates an `UnsafePinned`, with the `Default` value for T.
147 fn default() -> Self {
148 UnsafePinned::new(T::default())
149 }
150}
151
152#[unstable(feature = "unsafe_pinned", issue = "125735")]
153#[rustc_const_unstable(feature = "const_convert", issue = "143773")]
154const impl<T> From<T> for UnsafePinned<T> {
155 /// Creates a new `UnsafePinned<T>` containing the given value.
156 fn from(value: T) -> Self {
157 UnsafePinned::new(value)
158 }
159}
160
161#[unstable(feature = "unsafe_pinned", issue = "125735")]
162impl<T: ?Sized> fmt::Debug for UnsafePinned<T> {
163 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 f.debug_struct("UnsafePinned").finish_non_exhaustive()
165 }
166}
167
168#[unstable(feature = "coerce_unsized", issue = "18598")]
169// #[unstable(feature = "unsafe_pinned", issue = "125735")]
170impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafePinned<U>> for UnsafePinned<T> {}
171
172// Allow types that wrap `UnsafePinned` to also implement `DispatchFromDyn`
173// and become dyn-compatible method receivers.
174// Note that currently `UnsafePinned` itself cannot be a method receiver
175// because it does not implement Deref.
176// In other words:
177// `self: UnsafePinned<&Self>` won't work
178// `self: UnsafePinned<Self>` becomes possible
179// FIXME(unsafe_pinned) this logic is copied from UnsafeCell, is it still sound?
180#[unstable(feature = "dispatch_from_dyn", issue = "none")]
181// #[unstable(feature = "unsafe_pinned", issue = "125735")]
182impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafePinned<U>> for UnsafePinned<T> {}