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 mutable access to the contents of a shared `UnsafePinned`.
90    ///
91    /// This can be cast to a pointer of any kind. When creating references, you must uphold the
92    /// aliasing rules; see [`UnsafeCell`] for more discussion and caveats.
93    ///
94    /// [`UnsafeCell`]: crate::cell::UnsafeCell#aliasing-rules
95    ///
96    /// ```rust,no_run
97    /// #![feature(unsafe_pinned)]
98    /// use std::pin::UnsafePinned;
99    ///
100    /// unsafe {
101    ///     let mut x = UnsafePinned::new(0);
102    ///     let ptr = x.get();
103    ///     x.get_mut_unchecked().write(1);
104    ///     assert_eq!(ptr.read(), 1);
105    /// }
106    /// ```
107    #[inline(always)]
108    #[must_use]
109    #[unstable(feature = "unsafe_pinned", issue = "125735")]
110    pub const fn get(&self) -> *mut T {
111        self.value.get()
112    }
113
114    /// Gets an immutable pointer to the wrapped value.
115    ///
116    /// The difference from [`get`] is that this function accepts a raw pointer, which is useful to
117    /// avoid the creation of temporary references.
118    ///
119    /// [`get`]: UnsafePinned::get
120    #[inline(always)]
121    #[must_use]
122    #[unstable(feature = "unsafe_pinned", issue = "125735")]
123    pub const fn raw_get(this: *const Self) -> *const T {
124        this as *const T
125    }
126
127    /// Gets a mutable pointer to the wrapped value.
128    ///
129    /// The difference from [`get_mut_pinned`] and [`get_mut_unchecked`] is that this function
130    /// accepts a raw pointer, which is useful to avoid the creation of temporary references.
131    ///
132    /// [`get_mut_pinned`]: UnsafePinned::get_mut_pinned
133    /// [`get_mut_unchecked`]: UnsafePinned::get_mut_unchecked
134    #[inline(always)]
135    #[must_use]
136    #[unstable(feature = "unsafe_pinned", issue = "125735")]
137    pub const fn raw_get_mut(this: *mut Self) -> *mut T {
138        this as *mut T
139    }
140}
141
142#[unstable(feature = "unsafe_pinned", issue = "125735")]
143impl<T: Default> Default for UnsafePinned<T> {
144    /// Creates an `UnsafePinned`, with the `Default` value for T.
145    fn default() -> Self {
146        UnsafePinned::new(T::default())
147    }
148}
149
150#[unstable(feature = "unsafe_pinned", issue = "125735")]
151impl<T> From<T> for UnsafePinned<T> {
152    /// Creates a new `UnsafePinned<T>` containing the given value.
153    fn from(value: T) -> Self {
154        UnsafePinned::new(value)
155    }
156}
157
158#[unstable(feature = "unsafe_pinned", issue = "125735")]
159impl<T: ?Sized> fmt::Debug for UnsafePinned<T> {
160    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
161        f.debug_struct("UnsafePinned").finish_non_exhaustive()
162    }
163}
164
165#[unstable(feature = "coerce_unsized", issue = "18598")]
166// #[unstable(feature = "unsafe_pinned", issue = "125735")]
167impl<T: CoerceUnsized<U>, U> CoerceUnsized<UnsafePinned<U>> for UnsafePinned<T> {}
168
169// Allow types that wrap `UnsafePinned` to also implement `DispatchFromDyn`
170// and become dyn-compatible method receivers.
171// Note that currently `UnsafePinned` itself cannot be a method receiver
172// because it does not implement Deref.
173// In other words:
174// `self: UnsafePinned<&Self>` won't work
175// `self: UnsafePinned<Self>` becomes possible
176// FIXME(unsafe_pinned) this logic is copied from UnsafeCell, is it still sound?
177#[unstable(feature = "dispatch_from_dyn", issue = "none")]
178// #[unstable(feature = "unsafe_pinned", issue = "125735")]
179impl<T: DispatchFromDyn<U>, U> DispatchFromDyn<UnsafePinned<U>> for UnsafePinned<T> {}
180
181#[unstable(feature = "pointer_like_trait", issue = "none")]
182// #[unstable(feature = "unsafe_pinned", issue = "125735")]
183impl<T: PointerLike> PointerLike for UnsafePinned<T> {}
184
185// FIXME(unsafe_pinned): impl PinCoerceUnsized for UnsafePinned<T>?