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 [`mem::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 //! It is worth reiterating that [`Pin`] does *not* change the fact that the Rust compiler
28 //! considers all types movable. [`mem::swap`] remains callable for any `T`. Instead, `Pin`
29 //! prevents certain *values* (pointed to by pointers wrapped in `Pin`) from being
30 //! moved by making it impossible to call methods like [`mem::swap`] on them.
34 //! However, these restrictions are usually not necessary. Many types are always freely
35 //! movable, even when pinned, because they do not rely on having a stable address.
36 //! These types implement the [`Unpin`] auto-trait, which
37 //! nullifies the effect of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function
38 //! identically, as do `Pin<&mut T>` and `&mut T`.
40 //! Note that pinning and `Unpin` only affect the pointed-to type, not the pointer
41 //! type itself that got wrapped in `Pin`. For example, whether or not `Box<T>` is
42 //! `Unpin` has no affect on the behavior of `Pin<Box<T>>` (here, `T` is the
48 //! use std::pin::Pin;
49 //! use std::marker::PhantomPinned;
50 //! use std::ptr::NonNull;
52 //! // This is a self-referential struct since the slice field points to the data field.
53 //! // We cannot inform the compiler about that with a normal reference,
54 //! // since this pattern cannot be described with the usual borrowing rules.
55 //! // Instead we use a raw pointer, though one which is known to not be null,
56 //! // since we know it's pointing at the string.
57 //! struct Unmovable {
59 //! slice: NonNull<String>,
60 //! _pin: PhantomPinned,
64 //! // To ensure the data doesn't move when the function returns,
65 //! // we place it in the heap where it will stay for the lifetime of the object,
66 //! // and the only way to access it would be through a pointer to it.
67 //! fn new(data: String) -> Pin<Box<Self>> {
68 //! let res = Unmovable {
70 //! // we only create the pointer once the data is in place
71 //! // otherwise it will have already moved before we even started
72 //! slice: NonNull::dangling(),
73 //! _pin: PhantomPinned,
75 //! let mut boxed = Box::pin(res);
77 //! let slice = NonNull::from(&boxed.data);
78 //! // we know this is safe because modifying a field doesn't move the whole struct
80 //! let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
81 //! Pin::get_unchecked_mut(mut_ref).slice = slice;
87 //! let unmoved = Unmovable::new("hello".to_string());
88 //! // The pointer should point to the correct location,
89 //! // so long as the struct hasn't moved.
90 //! // Meanwhile, we are free to move the pointer around.
91 //! # #[allow(unused_mut)]
92 //! let mut still_unmoved = unmoved;
93 //! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
95 //! // Since our type doesn't implement Unpin, this will fail to compile:
96 //! // let new_unmoved = Unmovable::new("world".to_string());
97 //! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
100 //! # `Drop` guarantee
102 //! The purpose of pinning is to be able to rely on the placement of some data in memory.
103 //! To make this work, not just moving the data is restricted; deallocating, repurposing or
104 //! otherwise invalidating the memory used to store the data is restricted, too.
105 //! Concretely, for pinned data you have to maintain the invariant
106 //! that *its memory will not get invalidated from the momentit gets pinned until
107 //! when `drop` is called*. Memory can be invalidated by deallocation, but also by
108 //! replacing a `Some(v)` by `None`, or calling `Vec::set_len` to "kill" some elements
111 //! The purpose of this guarantee is to allow data structures that store pointers
112 //! to pinned data. For example, in an intrusive doubly-linked list, every element
113 //! will have pointers to its predecessor and successor in the list. Every element
114 //! will be pinned, because moving the elements around would invalidate the pointers.
115 //! Moreover, the `Drop` implementation of a linked list element will patch the pointers
116 //! of its predecessor and successor to remove itself from the list. Clearly, if an element
117 //! could be deallocated or overwritten without calling `drop`, the pointers into it
118 //! from its neighbouring elements would become invalid, which would break the data structure.
120 //! Notice that this guarantee does *not* mean that memory does not leak! It is still
121 //! completely okay not to ever call `drop` on a pinned element (e.g., you can still
122 //! call [`mem::forget`] on a `Pin<Box<T>>`). What you may not do is free or reuse the storage
123 //! without calling `drop`.
125 //! # `Drop` implementation
127 //! If your type relies on pinning (for example, because it contains internal
128 //! references, or because you are implementing something like the intrusive
129 //! doubly-linked list mentioned in the previous section), you have to be careful
130 //! when implementing `Drop`: notice that `drop` takes `&mut self`, but this
131 //! will be called even if your type was previously pinned! It is as if the
132 //! compiler automatically called `get_unchecked_mut`. This can never cause
133 //! a problem in safe code because implementing a type that relies on pinning
134 //! requires unsafe code, but be aware that deciding to make use of pinning
135 //! in your type (for example by implementing some operation on `Pin<&[mut] Self>`)
136 //! has consequences for your `Drop` implementation as well: if an element
137 //! of your type could have been pinned, you must treat Drop as implicitly taking
138 //! `Pin<&mut Self>`.
140 //! # Projections and Structural Pinning
142 //! One interesting question arises when considering pinning and "container types" --
143 //! types such as `Vec` or `Box` but also `RefCell`; types that serve as wrappers
144 //! around other types. When can such a type have a "projection" operation, an
145 //! operation with type `fn(Pin<&[mut] Container<T>>) -> Pin<&[mut] T>`?
146 //! This does not just apply to generic container types, even for normal structs
147 //! the question arises whether `fn(Pin<&[mut] Struct>) -> Pin<&[mut] Field>`
148 //! is an operation that can be soundly added to the API.
150 //! This question is closely related to the question of whether pinning is "structural":
151 //! when you have pinned a container, have you pinned its contents? Adding a
152 //! projection to the API answers that question with a "yes" by offering pinned access
155 //! In general, as the author of a type you get to decide whether pinning is structural, and
156 //! whether projections are provided. However, there are a couple requirements to be
157 //! upheld when adding projection operations:
159 //! 1. The container must only be [`Unpin`] if all the fields one can project to are
160 //! `Unpin`. This is the default, but `Unpin` is a safe trait, so as the author of
161 //! the container it is your responsibility *not* to add something like
162 //! `impl<T> Unpin for Container<T>`. (Notice that adding a projection operation
163 //! requires unsafe code, so the fact that `Unpin` is a safe trait does not break
164 //! the principle that you only have to worry about any of this if you use `unsafe`.)
165 //! 2. The destructor of the container must not move out of its argument. This is the exact
166 //! point that was raised in the [previous section][drop-impl]: `drop` takes `&mut self`,
167 //! but the container (and hence its fields) might have been pinned before.
168 //! You have to guarantee that you do not move a field inside your `Drop` implementation.
169 //! 3. Your container type must *not* be `#[repr(packed)]`. Packed structs have their fields
170 //! moved around when they are dropped to properly align them, which is in conflict with
171 //! claiming that the fields are pinned when your struct is.
172 //! 4. You must make sure that you uphold the [`Drop` guarantee][drop-guarantee]:
173 //! you must make sure that, once your container is pinned, the memory containing the
174 //! content is not overwritten or deallocated without calling the content's destructors.
175 //! This can be tricky, as witnessed by `VecDeque`: the destructor of `VecDeque` can fail
176 //! to call `drop` on all elements if one of the destructors panics. This violates the
177 //! `Drop` guarantee, because it can lead to elements being deallocated without
178 //! their destructor being called.
179 //! 5. You must not offer any other operations that could lead to data being moved out of
180 //! the fields when your type is pinned. This is usually not a concern, but can become
181 //! tricky when interior mutability is involved. For example, imagine `RefCell`
182 //! would have a method `fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>`.
183 //! This would be catastrophic, because it is possible to move out of a pinned
184 //! `RefCell`: from `x: Pin<&mut RefCell<T>>`, use `let y = x.into_ref().get_ref()` to obtain
185 //! `y: &RefCell<T>`, and from there use `y.borrow_mut().deref_mut()` to obtain `&mut T`
186 //! which can be used with [`mem::swap`].
188 //! On the other hand, if you decide *not* to offer any pinning projections, you
189 //! are free to do `impl<T> Unpin for Container<T>`. In the standard library,
190 //! we do this for all pointer types: `Box<T>: Unpin` holds for all `T`.
191 //! It makes a lot of sense to do this for pointer types, because moving the `Box<T>`
192 //! does not actually move the `T`: the `Box<T>` can be freely movable even if the `T`
193 //! is not. In fact, even `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves,
194 //! for the same reason.
196 //! [`Pin`]: struct.Pin.html
197 //! [`Unpin`]: ../../std/marker/trait.Unpin.html
198 //! [`mem::swap`]: ../../std/mem/fn.swap.html
199 //! [`mem::forget`]: ../../std/mem/fn.forget.html
200 //! [`Box`]: ../../std/boxed/struct.Box.html
201 //! [drop-impl]: #drop-implementation
202 //! [drop-guarantee]: #drop-guarantee
204 #![stable(feature = "pin", since = "1.33.0")]
207 use marker::{Sized, Unpin};
208 use cmp::{self, PartialEq, PartialOrd};
209 use ops::{Deref, DerefMut, Receiver, CoerceUnsized, DispatchFromDyn};
211 /// A pinned pointer.
213 /// This is a wrapper around a kind of pointer which makes that pointer "pin" its
214 /// value in place, preventing the value referenced by that pointer from being moved
215 /// unless it implements [`Unpin`].
217 /// See the [`pin` module] documentation for further explanation on pinning.
219 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
220 /// [`pin` module]: ../../std/pin/index.html
222 // Note: the derives below, and the explicit `PartialEq` and `PartialOrd`
223 // implementations, are allowed because they all only use `&P`, so they cannot move
224 // the value behind `pointer`.
225 #[stable(feature = "pin", since = "1.33.0")]
226 #[cfg_attr(not(stage0), lang = "pin")]
229 #[derive(Copy, Clone, Hash, Eq, Ord)]
234 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
235 impl<P, Q> PartialEq<Pin<Q>> for Pin<P>
239 fn eq(&self, other: &Pin<Q>) -> bool {
240 self.pointer == other.pointer
243 fn ne(&self, other: &Pin<Q>) -> bool {
244 self.pointer != other.pointer
248 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
249 impl<P, Q> PartialOrd<Pin<Q>> for Pin<P>
253 fn partial_cmp(&self, other: &Pin<Q>) -> Option<cmp::Ordering> {
254 self.pointer.partial_cmp(&other.pointer)
257 fn lt(&self, other: &Pin<Q>) -> bool {
258 self.pointer < other.pointer
261 fn le(&self, other: &Pin<Q>) -> bool {
262 self.pointer <= other.pointer
265 fn gt(&self, other: &Pin<Q>) -> bool {
266 self.pointer > other.pointer
269 fn ge(&self, other: &Pin<Q>) -> bool {
270 self.pointer >= other.pointer
274 impl<P: Deref> Pin<P>
278 /// Construct a new `Pin` around a pointer to some data of a type that
279 /// implements [`Unpin`].
281 /// Unlike `Pin::new_unchecked`, this method is safe because the pointer
282 /// `P` dereferences to an [`Unpin`] type, which nullifies the pinning guarantees.
284 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
285 #[stable(feature = "pin", since = "1.33.0")]
287 pub fn new(pointer: P) -> Pin<P> {
288 // Safety: the value pointed to is `Unpin`, and so has no requirements
290 unsafe { Pin::new_unchecked(pointer) }
294 impl<P: Deref> Pin<P> {
295 /// Construct a new `Pin` around a reference to some data of a type that
296 /// may or may not implement `Unpin`.
300 /// This constructor is unsafe because we cannot guarantee that the data
301 /// pointed to by `pointer` is pinned forever. If the constructed `Pin<P>` does
302 /// not guarantee that the data `P` points to is pinned, constructing a
303 /// `Pin<P>` is unsafe. In particular, calling `Pin::new_unchecked`
304 /// on an `&'a mut T` is unsafe because while you are able to pin it for the given
305 /// lifetime `'a`, you have no control over whether it is kept pinned once `'a`
306 /// ends. A value, once pinned, must remain pinned forever
307 /// (unless its type implements `Unpin`).
309 /// By using this method, you are making a promise about the `P::Deref` and
310 /// `P::DerefMut` implementations, if they exist. Most importantly, they
311 /// must not move out of their `self` arguments: `Pin::as_mut` and `Pin::as_ref`
312 /// will call `DerefMut::deref_mut` and `Deref::deref` *on the pinned pointer*
313 /// and expect these methods to uphold the pinning invariants.
314 /// Moreover, by calling this method you promise that the reference `P`
315 /// dereferences to will not be moved out of again; in particular, it
316 /// must not be possible to obtain a `&mut P::Target` and then
317 /// move out of that reference (using, for example [`mem::swap`]).
319 /// For example, the following is a *violation* of `Pin`'s safety:
322 /// use std::pin::Pin;
324 /// fn foo<T>(mut a: T, mut b: T) {
325 /// unsafe { let p = Pin::new_unchecked(&mut a); } // should mean `a` can never move again
326 /// mem::swap(&mut a, &mut b);
327 /// // the address of `a` changed to `b`'s stack slot, so `a` got moved even
328 /// // though we have previously pinned it!
332 /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
335 /// [`mem::swap`]: ../../std/mem/fn.swap.html
336 #[stable(feature = "pin", since = "1.33.0")]
338 pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
342 /// Gets a pinned shared reference from this pinned pointer.
344 /// This is a generic method to go from `&Pin<SmartPointer<T>>` to `Pin<&T>`.
345 /// It is safe because, as part of the contract of `Pin::new_unchecked`,
346 /// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
347 /// "Malicious" implementations of `SmartPointer::Deref` are likewise
348 /// ruled out by the contract of `Pin::new_unchecked`.
349 #[stable(feature = "pin", since = "1.33.0")]
351 pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
352 unsafe { Pin::new_unchecked(&*self.pointer) }
356 impl<P: DerefMut> Pin<P> {
357 /// Gets a pinned mutable reference from this pinned pointer.
359 /// This is a generic method to go from `&mut Pin<SmartPointer<T>>` to `Pin<&mut T>`.
360 /// It is safe because, as part of the contract of `Pin::new_unchecked`,
361 /// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
362 /// "Malicious" implementations of `SmartPointer::DerefMut` are likewise
363 /// ruled out by the contract of `Pin::new_unchecked`.
364 #[stable(feature = "pin", since = "1.33.0")]
366 pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
367 unsafe { Pin::new_unchecked(&mut *self.pointer) }
370 /// Assigns a new value to the memory behind the pinned reference.
372 /// This overwrites pinned data, but that is okay: its destructor gets
373 /// run before being overwritten, so no pinning guarantee is violated.
374 #[stable(feature = "pin", since = "1.33.0")]
376 pub fn set(self: &mut Pin<P>, value: P::Target)
380 *(self.pointer) = value;
384 impl<'a, T: ?Sized> Pin<&'a T> {
385 /// Constructs a new pin by mapping the interior value.
387 /// For example, if you wanted to get a `Pin` of a field of something,
388 /// you could use this to get access to that field in one line of code.
389 /// However, there are several gotchas with these "pinning projections";
390 /// see the [`pin` module] documentation for further details on that topic.
394 /// This function is unsafe. You must guarantee that the data you return
395 /// will not move so long as the argument value does not move (for example,
396 /// because it is one of the fields of that value), and also that you do
397 /// not move out of the argument you receive to the interior function.
399 /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
400 #[stable(feature = "pin", since = "1.33.0")]
401 pub unsafe fn map_unchecked<U, F>(self: Pin<&'a T>, func: F) -> Pin<&'a U> where
404 let pointer = &*self.pointer;
405 let new_pointer = func(pointer);
406 Pin::new_unchecked(new_pointer)
409 /// Gets a shared reference out of a pin.
411 /// This is safe because it is not possible to move out of a shared reference.
412 /// It may seem like there is an issue here with interior mutability: in fact,
413 /// it *is* possible to move a `T` out of a `&RefCell<T>`. However, this is
414 /// not a problem as long as there does not also exist a `Pin<&T>` pointing
415 /// to the same data, and `RefCell` does not let you create a pinned reference
416 /// to its contents. See the discussion on ["pinning projections"] for further
419 /// Note: `Pin` also implements `Deref` to the target, which can be used
420 /// to access the inner value. However, `Deref` only provides a reference
421 /// that lives for as long as the borrow of the `Pin`, not the lifetime of
422 /// the `Pin` itself. This method allows turning the `Pin` into a reference
423 /// with the same lifetime as the original `Pin`.
425 /// ["pinning projections"]: ../../std/pin/index.html#projections-and-structural-pinning
426 #[stable(feature = "pin", since = "1.33.0")]
428 pub fn get_ref(self: Pin<&'a T>) -> &'a T {
433 impl<'a, T: ?Sized> Pin<&'a mut T> {
434 /// Converts this `Pin<&mut T>` into a `Pin<&T>` with the same lifetime.
435 #[stable(feature = "pin", since = "1.33.0")]
437 pub fn into_ref(self: Pin<&'a mut T>) -> Pin<&'a T> {
438 Pin { pointer: self.pointer }
441 /// Gets a mutable reference to the data inside of this `Pin`.
443 /// This requires that the data inside this `Pin` is `Unpin`.
445 /// Note: `Pin` also implements `DerefMut` to the data, which can be used
446 /// to access the inner value. However, `DerefMut` only provides a reference
447 /// that lives for as long as the borrow of the `Pin`, not the lifetime of
448 /// the `Pin` itself. This method allows turning the `Pin` into a reference
449 /// with the same lifetime as the original `Pin`.
450 #[stable(feature = "pin", since = "1.33.0")]
452 pub fn get_mut(self: Pin<&'a mut T>) -> &'a mut T
458 /// Gets a mutable reference to the data inside of this `Pin`.
462 /// This function is unsafe. You must guarantee that you will never move
463 /// the data out of the mutable reference you receive when you call this
464 /// function, so that the invariants on the `Pin` type can be upheld.
466 /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
468 #[stable(feature = "pin", since = "1.33.0")]
470 pub unsafe fn get_unchecked_mut(self: Pin<&'a mut T>) -> &'a mut T {
474 /// Construct a new pin by mapping the interior value.
476 /// For example, if you wanted to get a `Pin` of a field of something,
477 /// you could use this to get access to that field in one line of code.
478 /// However, there are several gotchas with these "pinning projections";
479 /// see the [`pin` module] documentation for further details on that topic.
483 /// This function is unsafe. You must guarantee that the data you return
484 /// will not move so long as the argument value does not move (for example,
485 /// because it is one of the fields of that value), and also that you do
486 /// not move out of the argument you receive to the interior function.
488 /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
489 #[stable(feature = "pin", since = "1.33.0")]
490 pub unsafe fn map_unchecked_mut<U, F>(self: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
491 F: FnOnce(&mut T) -> &mut U,
493 let pointer = Pin::get_unchecked_mut(self);
494 let new_pointer = func(pointer);
495 Pin::new_unchecked(new_pointer)
499 #[stable(feature = "pin", since = "1.33.0")]
500 impl<P: Deref> Deref for Pin<P> {
501 type Target = P::Target;
502 fn deref(&self) -> &P::Target {
503 Pin::get_ref(Pin::as_ref(self))
507 #[stable(feature = "pin", since = "1.33.0")]
508 impl<P: DerefMut> DerefMut for Pin<P>
512 fn deref_mut(&mut self) -> &mut P::Target {
513 Pin::get_mut(Pin::as_mut(self))
517 #[unstable(feature = "receiver_trait", issue = "0")]
518 impl<P: Receiver> Receiver for Pin<P> {}
520 #[stable(feature = "pin", since = "1.33.0")]
521 impl<P: fmt::Debug> fmt::Debug for Pin<P> {
522 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
523 fmt::Debug::fmt(&self.pointer, f)
527 #[stable(feature = "pin", since = "1.33.0")]
528 impl<P: fmt::Display> fmt::Display for Pin<P> {
529 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
530 fmt::Display::fmt(&self.pointer, f)
534 #[stable(feature = "pin", since = "1.33.0")]
535 impl<P: fmt::Pointer> fmt::Pointer for Pin<P> {
536 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
537 fmt::Pointer::fmt(&self.pointer, f)
541 // Note: this means that any impl of `CoerceUnsized` that allows coercing from
542 // a type that impls `Deref<Target=impl !Unpin>` to a type that impls
543 // `Deref<Target=Unpin>` is unsound. Any such impl would probably be unsound
544 // for other reasons, though, so we just need to take care not to allow such
545 // impls to land in std.
546 #[stable(feature = "pin", since = "1.33.0")]
547 impl<P, U> CoerceUnsized<Pin<U>> for Pin<P>
552 #[stable(feature = "pin", since = "1.33.0")]
553 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
555 P: DispatchFromDyn<U>,