1 //! Types which pin data to its location in memory
3 //! It is sometimes useful to have objects that are guaranteed to not move,
4 //! in the sense that their placement in memory does not change, and can thus be relied upon.
6 //! A prime example of such a scenario would be building self-referential structs,
7 //! since moving an object with pointers to itself will invalidate them,
8 //! which could cause undefined behavior.
10 //! By default, all types in Rust are movable. Rust allows passing all types by-value,
11 //! and common smart-pointer types such as `Box`, `Rc`, and `&mut` allow replacing and
12 //! moving the values they contain. In order to prevent objects from moving, they must
13 //! be pinned by wrapping a pointer to the data in the [`Pin`] type.
14 //! Doing this prohibits moving the value behind the pointer.
15 //! For example, `Pin<Box<T>>` functions much like a regular `Box<T>`,
16 //! but doesn't allow moving `T`. The pointer value itself (the `Box`) can still be moved,
17 //! but the value behind it cannot.
19 //! Since data can be moved out of `&mut` and `Box` with functions such as [`swap`],
20 //! changing the location of the underlying data, [`Pin`] prohibits accessing the
21 //! underlying pointer type (the `&mut` or `Box`) directly, and provides its own set of
22 //! APIs for accessing and using the value. [`Pin`] also guarantees that no other
23 //! functions will move the pointed-to value. This allows for the creation of
24 //! self-references and other special behaviors that are only possible for unmovable
27 //! However, these restrictions are usually not necessary. Many types are always freely
28 //! movable. These types implement the [`Unpin`] auto-trait, which nullifies the effect
29 //! of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function identically, as do
30 //! `Pin<&mut T>` and `&mut T`.
32 //! Note that pinning and `Unpin` only affect the pointed-to type. For example, whether
33 //! or not `Box<T>` is `Unpin` has no affect on the behavior of `Pin<Box<T>>`. Similarly,
34 //! `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves, even though the
35 //! `T` underneath them isn't, because the pointers in `Pin<Box<_>>` and `Pin<&mut _>`
36 //! are always freely movable, even if the data they point to isn't.
38 //! [`Pin`]: struct.Pin.html
39 //! [`Unpin`]: ../../std/marker/trait.Unpin.html
40 //! [`swap`]: ../../std/mem/fn.swap.html
41 //! [`Box`]: ../../std/boxed/struct.Box.html
46 //! use std::pin::Pin;
47 //! use std::marker::PhantomPinned;
48 //! use std::ptr::NonNull;
50 //! // This is a self-referential struct since the slice field points to the data field.
51 //! // We cannot inform the compiler about that with a normal reference,
52 //! // since this pattern cannot be described with the usual borrowing rules.
53 //! // Instead we use a raw pointer, though one which is known to not be null,
54 //! // since we know it's pointing at the string.
55 //! struct Unmovable {
57 //! slice: NonNull<String>,
58 //! _pin: PhantomPinned,
62 //! // To ensure the data doesn't move when the function returns,
63 //! // we place it in the heap where it will stay for the lifetime of the object,
64 //! // and the only way to access it would be through a pointer to it.
65 //! fn new(data: String) -> Pin<Box<Self>> {
66 //! let res = Unmovable {
68 //! // we only create the pointer once the data is in place
69 //! // otherwise it will have already moved before we even started
70 //! slice: NonNull::dangling(),
71 //! _pin: PhantomPinned,
73 //! let mut boxed = Box::pin(res);
75 //! let slice = NonNull::from(&boxed.data);
76 //! // we know this is safe because modifying a field doesn't move the whole struct
78 //! let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
79 //! Pin::get_unchecked_mut(mut_ref).slice = slice;
85 //! let unmoved = Unmovable::new("hello".to_string());
86 //! // The pointer should point to the correct location,
87 //! // so long as the struct hasn't moved.
88 //! // Meanwhile, we are free to move the pointer around.
89 //! # #[allow(unused_mut)]
90 //! let mut still_unmoved = unmoved;
91 //! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
93 //! // Since our type doesn't implement Unpin, this will fail to compile:
94 //! // let new_unmoved = Unmovable::new("world".to_string());
95 //! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
98 #![stable(feature = "pin", since = "1.33.0")]
101 use marker::{Sized, Unpin};
102 use cmp::{self, PartialEq, PartialOrd};
103 use ops::{Deref, DerefMut, Receiver, CoerceUnsized, DispatchFromDyn};
105 /// A pinned pointer.
107 /// This is a wrapper around a kind of pointer which makes that pointer "pin" its
108 /// value in place, preventing the value referenced by that pointer from being moved
109 /// unless it implements [`Unpin`].
111 /// See the [`pin` module] documentation for further explanation on pinning.
113 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
114 /// [`pin` module]: ../../std/pin/index.html
116 // Note: the derives below, and the explicit `PartialEq` and `PartialOrd`
117 // implementations, are allowed because they all only use `&P`, so they cannot move
118 // the value behind `pointer`.
119 #[stable(feature = "pin", since = "1.33.0")]
120 #[cfg_attr(not(stage0), lang = "pin")]
123 #[derive(Copy, Clone, Hash, Eq, Ord)]
128 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
129 impl<P, Q> PartialEq<Pin<Q>> for Pin<P>
133 fn eq(&self, other: &Pin<Q>) -> bool {
134 self.pointer == other.pointer
137 fn ne(&self, other: &Pin<Q>) -> bool {
138 self.pointer != other.pointer
142 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
143 impl<P, Q> PartialOrd<Pin<Q>> for Pin<P>
147 fn partial_cmp(&self, other: &Pin<Q>) -> Option<cmp::Ordering> {
148 self.pointer.partial_cmp(&other.pointer)
151 fn lt(&self, other: &Pin<Q>) -> bool {
152 self.pointer < other.pointer
155 fn le(&self, other: &Pin<Q>) -> bool {
156 self.pointer <= other.pointer
159 fn gt(&self, other: &Pin<Q>) -> bool {
160 self.pointer > other.pointer
163 fn ge(&self, other: &Pin<Q>) -> bool {
164 self.pointer >= other.pointer
168 impl<P: Deref> Pin<P>
172 /// Construct a new `Pin` around a pointer to some data of a type that
173 /// implements `Unpin`.
174 #[stable(feature = "pin", since = "1.33.0")]
176 pub fn new(pointer: P) -> Pin<P> {
177 // Safety: the value pointed to is `Unpin`, and so has no requirements
179 unsafe { Pin::new_unchecked(pointer) }
183 impl<P: Deref> Pin<P> {
184 /// Construct a new `Pin` around a reference to some data of a type that
185 /// may or may not implement `Unpin`.
189 /// This constructor is unsafe because we cannot guarantee that the data
190 /// pointed to by `pointer` is pinned. If the constructed `Pin<P>` does
191 /// not guarantee that the data `P` points to is pinned, constructing a
192 /// `Pin<P>` is undefined behavior.
194 /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
196 #[stable(feature = "pin", since = "1.33.0")]
198 pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
202 /// Gets a pinned shared reference from this pinned pointer.
203 #[stable(feature = "pin", since = "1.33.0")]
205 pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
206 unsafe { Pin::new_unchecked(&*self.pointer) }
210 impl<P: DerefMut> Pin<P> {
211 /// Gets a pinned mutable reference from this pinned pointer.
212 #[stable(feature = "pin", since = "1.33.0")]
214 pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
215 unsafe { Pin::new_unchecked(&mut *self.pointer) }
218 /// Assign a new value to the memory behind the pinned reference.
219 #[stable(feature = "pin", since = "1.33.0")]
221 pub fn set(self: &mut Pin<P>, value: P::Target)
225 *(self.pointer) = value;
229 impl<'a, T: ?Sized> Pin<&'a T> {
230 /// Construct a new pin by mapping the interior value.
232 /// For example, if you wanted to get a `Pin` of a field of something,
233 /// you could use this to get access to that field in one line of code.
237 /// This function is unsafe. You must guarantee that the data you return
238 /// will not move so long as the argument value does not move (for example,
239 /// because it is one of the fields of that value), and also that you do
240 /// not move out of the argument you receive to the interior function.
241 #[stable(feature = "pin", since = "1.33.0")]
242 pub unsafe fn map_unchecked<U, F>(self: Pin<&'a T>, func: F) -> Pin<&'a U> where
245 let pointer = &*self.pointer;
246 let new_pointer = func(pointer);
247 Pin::new_unchecked(new_pointer)
250 /// Gets a shared reference out of a pin.
252 /// Note: `Pin` also implements `Deref` to the target, which can be used
253 /// to access the inner value. However, `Deref` only provides a reference
254 /// that lives for as long as the borrow of the `Pin`, not the lifetime of
255 /// the `Pin` itself. This method allows turning the `Pin` into a reference
256 /// with the same lifetime as the original `Pin`.
257 #[stable(feature = "pin", since = "1.33.0")]
259 pub fn get_ref(self: Pin<&'a T>) -> &'a T {
264 impl<'a, T: ?Sized> Pin<&'a mut T> {
265 /// Converts this `Pin<&mut T>` into a `Pin<&T>` with the same lifetime.
266 #[stable(feature = "pin", since = "1.33.0")]
268 pub fn into_ref(self: Pin<&'a mut T>) -> Pin<&'a T> {
269 Pin { pointer: self.pointer }
272 /// Gets a mutable reference to the data inside of this `Pin`.
274 /// This requires that the data inside this `Pin` is `Unpin`.
276 /// Note: `Pin` also implements `DerefMut` to the data, which can be used
277 /// to access the inner value. However, `DerefMut` only provides a reference
278 /// that lives for as long as the borrow of the `Pin`, not the lifetime of
279 /// the `Pin` itself. This method allows turning the `Pin` into a reference
280 /// with the same lifetime as the original `Pin`.
281 #[stable(feature = "pin", since = "1.33.0")]
283 pub fn get_mut(self: Pin<&'a mut T>) -> &'a mut T
289 /// Gets a mutable reference to the data inside of this `Pin`.
293 /// This function is unsafe. You must guarantee that you will never move
294 /// the data out of the mutable reference you receive when you call this
295 /// function, so that the invariants on the `Pin` type can be upheld.
297 /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
299 #[stable(feature = "pin", since = "1.33.0")]
301 pub unsafe fn get_unchecked_mut(self: Pin<&'a mut T>) -> &'a mut T {
305 /// Construct a new pin by mapping the interior value.
307 /// For example, if you wanted to get a `Pin` of a field of something,
308 /// you could use this to get access to that field in one line of code.
312 /// This function is unsafe. You must guarantee that the data you return
313 /// will not move so long as the argument value does not move (for example,
314 /// because it is one of the fields of that value), and also that you do
315 /// not move out of the argument you receive to the interior function.
316 #[stable(feature = "pin", since = "1.33.0")]
317 pub unsafe fn map_unchecked_mut<U, F>(self: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
318 F: FnOnce(&mut T) -> &mut U,
320 let pointer = Pin::get_unchecked_mut(self);
321 let new_pointer = func(pointer);
322 Pin::new_unchecked(new_pointer)
326 #[stable(feature = "pin", since = "1.33.0")]
327 impl<P: Deref> Deref for Pin<P> {
328 type Target = P::Target;
329 fn deref(&self) -> &P::Target {
330 Pin::get_ref(Pin::as_ref(self))
334 #[stable(feature = "pin", since = "1.33.0")]
335 impl<P: DerefMut> DerefMut for Pin<P>
339 fn deref_mut(&mut self) -> &mut P::Target {
340 Pin::get_mut(Pin::as_mut(self))
344 #[unstable(feature = "receiver_trait", issue = "0")]
345 impl<P: Receiver> Receiver for Pin<P> {}
347 #[stable(feature = "pin", since = "1.33.0")]
348 impl<P: fmt::Debug> fmt::Debug for Pin<P> {
349 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
350 fmt::Debug::fmt(&self.pointer, f)
354 #[stable(feature = "pin", since = "1.33.0")]
355 impl<P: fmt::Display> fmt::Display for Pin<P> {
356 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
357 fmt::Display::fmt(&self.pointer, f)
361 #[stable(feature = "pin", since = "1.33.0")]
362 impl<P: fmt::Pointer> fmt::Pointer for Pin<P> {
363 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
364 fmt::Pointer::fmt(&self.pointer, f)
368 // Note: this means that any impl of `CoerceUnsized` that allows coercing from
369 // a type that impls `Deref<Target=impl !Unpin>` to a type that impls
370 // `Deref<Target=Unpin>` is unsound. Any such impl would probably be unsound
371 // for other reasons, though, so we just need to take care not to allow such
372 // impls to land in std.
373 #[stable(feature = "pin", since = "1.33.0")]
374 impl<P, U> CoerceUnsized<Pin<U>> for Pin<P>
379 #[stable(feature = "pin", since = "1.33.0")]
380 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
382 P: DispatchFromDyn<U>,