]> git.lizzy.rs Git - rust.git/blob - library/core/src/pin.rs
Merge commit '70c0f90453701e7d6d9b99aaa1fc6a765937b736' into clippyup
[rust.git] / library / core / src / pin.rs
1 //! Types that pin data to its location in memory.
2 //!
3 //! It is sometimes useful to have objects that are guaranteed not to move,
4 //! in the sense that their placement in memory does not change, and can thus be relied upon.
5 //! A prime example of such a scenario would be building self-referential structs,
6 //! as moving an object with pointers to itself will invalidate them, which could cause undefined
7 //! behavior.
8 //!
9 //! At a high level, a [`Pin<P>`] ensures that the pointee of any pointer type
10 //! `P` has a stable location in memory, meaning it cannot be moved elsewhere
11 //! and its memory cannot be deallocated until it gets dropped. We say that the
12 //! pointee is "pinned". Things get more subtle when discussing types that
13 //! combine pinned with non-pinned data; [see below](#projections-and-structural-pinning)
14 //! for more details.
15 //!
16 //! By default, all types in Rust are movable. Rust allows passing all types by-value,
17 //! and common smart-pointer types such as [`Box<T>`] and `&mut T` allow replacing and
18 //! moving the values they contain: you can move out of a [`Box<T>`], or you can use [`mem::swap`].
19 //! [`Pin<P>`] wraps a pointer type `P`, so [`Pin`]`<`[`Box`]`<T>>` functions much like a regular
20 //! [`Box<T>`]: when a [`Pin`]`<`[`Box`]`<T>>` gets dropped, so do its contents, and the memory gets
21 //! deallocated. Similarly, [`Pin`]`<&mut T>` is a lot like `&mut T`. However, [`Pin<P>`] does
22 //! not let clients actually obtain a [`Box<T>`] or `&mut T` to pinned data, which implies that you
23 //! cannot use operations such as [`mem::swap`]:
24 //!
25 //! ```
26 //! use std::pin::Pin;
27 //! fn swap_pins<T>(x: Pin<&mut T>, y: Pin<&mut T>) {
28 //!     // `mem::swap` needs `&mut T`, but we cannot get it.
29 //!     // We are stuck, we cannot swap the contents of these references.
30 //!     // We could use `Pin::get_unchecked_mut`, but that is unsafe for a reason:
31 //!     // we are not allowed to use it for moving things out of the `Pin`.
32 //! }
33 //! ```
34 //!
35 //! It is worth reiterating that [`Pin<P>`] does *not* change the fact that a Rust compiler
36 //! considers all types movable. [`mem::swap`] remains callable for any `T`. Instead, [`Pin<P>`]
37 //! prevents certain *values* (pointed to by pointers wrapped in [`Pin<P>`]) from being
38 //! moved by making it impossible to call methods that require `&mut T` on them
39 //! (like [`mem::swap`]).
40 //!
41 //! [`Pin<P>`] can be used to wrap any pointer type `P`, and as such it interacts with
42 //! [`Deref`] and [`DerefMut`]. A [`Pin<P>`] where `P: Deref` should be considered
43 //! as a "`P`-style pointer" to a pinned `P::Target` -- so, a [`Pin`]`<`[`Box`]`<T>>` is
44 //! an owned pointer to a pinned `T`, and a [`Pin`]`<`[`Rc`]`<T>>` is a reference-counted
45 //! pointer to a pinned `T`.
46 //! For correctness, [`Pin<P>`] relies on the implementations of [`Deref`] and
47 //! [`DerefMut`] not to move out of their `self` parameter, and only ever to
48 //! return a pointer to pinned data when they are called on a pinned pointer.
49 //!
50 //! # `Unpin`
51 //!
52 //! Many types are always freely movable, even when pinned, because they do not
53 //! rely on having a stable address. This includes all the basic types (like
54 //! [`bool`], [`i32`], and references) as well as types consisting solely of these
55 //! types. Types that do not care about pinning implement the [`Unpin`]
56 //! auto-trait, which cancels the effect of [`Pin<P>`]. For `T: Unpin`,
57 //! [`Pin`]`<`[`Box`]`<T>>` and [`Box<T>`] function identically, as do [`Pin`]`<&mut T>` and
58 //! `&mut T`.
59 //!
60 //! Note that pinning and [`Unpin`] only affect the pointed-to type `P::Target`, not the pointer
61 //! type `P` itself that got wrapped in [`Pin<P>`]. For example, whether or not [`Box<T>`] is
62 //! [`Unpin`] has no effect on the behavior of [`Pin`]`<`[`Box`]`<T>>` (here, `T` is the
63 //! pointed-to type).
64 //!
65 //! # Example: self-referential struct
66 //!
67 //! Before we go into more details to explain the guarantees and choices
68 //! associated with `Pin<T>`, we discuss some examples for how it might be used.
69 //! Feel free to [skip to where the theoretical discussion continues](#drop-guarantee).
70 //!
71 //! ```rust
72 //! use std::pin::Pin;
73 //! use std::marker::PhantomPinned;
74 //! use std::ptr::NonNull;
75 //!
76 //! // This is a self-referential struct because the slice field points to the data field.
77 //! // We cannot inform the compiler about that with a normal reference,
78 //! // as this pattern cannot be described with the usual borrowing rules.
79 //! // Instead we use a raw pointer, though one which is known not to be null,
80 //! // as we know it's pointing at the string.
81 //! struct Unmovable {
82 //!     data: String,
83 //!     slice: NonNull<String>,
84 //!     _pin: PhantomPinned,
85 //! }
86 //!
87 //! impl Unmovable {
88 //!     // To ensure the data doesn't move when the function returns,
89 //!     // we place it in the heap where it will stay for the lifetime of the object,
90 //!     // and the only way to access it would be through a pointer to it.
91 //!     fn new(data: String) -> Pin<Box<Self>> {
92 //!         let res = Unmovable {
93 //!             data,
94 //!             // we only create the pointer once the data is in place
95 //!             // otherwise it will have already moved before we even started
96 //!             slice: NonNull::dangling(),
97 //!             _pin: PhantomPinned,
98 //!         };
99 //!         let mut boxed = Box::pin(res);
100 //!
101 //!         let slice = NonNull::from(&boxed.data);
102 //!         // we know this is safe because modifying a field doesn't move the whole struct
103 //!         unsafe {
104 //!             let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
105 //!             Pin::get_unchecked_mut(mut_ref).slice = slice;
106 //!         }
107 //!         boxed
108 //!     }
109 //! }
110 //!
111 //! let unmoved = Unmovable::new("hello".to_string());
112 //! // The pointer should point to the correct location,
113 //! // so long as the struct hasn't moved.
114 //! // Meanwhile, we are free to move the pointer around.
115 //! # #[allow(unused_mut)]
116 //! let mut still_unmoved = unmoved;
117 //! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
118 //!
119 //! // Since our type doesn't implement Unpin, this will fail to compile:
120 //! // let mut new_unmoved = Unmovable::new("world".to_string());
121 //! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
122 //! ```
123 //!
124 //! # Example: intrusive doubly-linked list
125 //!
126 //! In an intrusive doubly-linked list, the collection does not actually allocate
127 //! the memory for the elements itself. Allocation is controlled by the clients,
128 //! and elements can live on a stack frame that lives shorter than the collection does.
129 //!
130 //! To make this work, every element has pointers to its predecessor and successor in
131 //! the list. Elements can only be added when they are pinned, because moving the elements
132 //! around would invalidate the pointers. Moreover, the [`Drop`] implementation of a linked
133 //! list element will patch the pointers of its predecessor and successor to remove itself
134 //! from the list.
135 //!
136 //! Crucially, we have to be able to rely on [`drop`] being called. If an element
137 //! could be deallocated or otherwise invalidated without calling [`drop`], the pointers into it
138 //! from its neighboring elements would become invalid, which would break the data structure.
139 //!
140 //! Therefore, pinning also comes with a [`drop`]-related guarantee.
141 //!
142 //! # `Drop` guarantee
143 //!
144 //! The purpose of pinning is to be able to rely on the placement of some data in memory.
145 //! To make this work, not just moving the data is restricted; deallocating, repurposing, or
146 //! otherwise invalidating the memory used to store the data is restricted, too.
147 //! Concretely, for pinned data you have to maintain the invariant
148 //! that *its memory will not get invalidated or repurposed from the moment it gets pinned until
149 //! when [`drop`] is called*.  Only once [`drop`] returns or panics, the memory may be reused.
150 //!
151 //! Memory can be "invalidated" by deallocation, but also by
152 //! replacing a [`Some(v)`] by [`None`], or calling [`Vec::set_len`] to "kill" some elements
153 //! off of a vector. It can be repurposed by using [`ptr::write`] to overwrite it without
154 //! calling the destructor first. None of this is allowed for pinned data without calling [`drop`].
155 //!
156 //! This is exactly the kind of guarantee that the intrusive linked list from the previous
157 //! section needs to function correctly.
158 //!
159 //! Notice that this guarantee does *not* mean that memory does not leak! It is still
160 //! completely okay not ever to call [`drop`] on a pinned element (e.g., you can still
161 //! call [`mem::forget`] on a [`Pin`]`<`[`Box`]`<T>>`). In the example of the doubly-linked
162 //! list, that element would just stay in the list. However you may not free or reuse the storage
163 //! *without calling [`drop`]*.
164 //!
165 //! # `Drop` implementation
166 //!
167 //! If your type uses pinning (such as the two examples above), you have to be careful
168 //! when implementing [`Drop`]. The [`drop`] function takes `&mut self`, but this
169 //! is called *even if your type was previously pinned*! It is as if the
170 //! compiler automatically called [`Pin::get_unchecked_mut`].
171 //!
172 //! This can never cause a problem in safe code because implementing a type that
173 //! relies on pinning requires unsafe code, but be aware that deciding to make
174 //! use of pinning in your type (for example by implementing some operation on
175 //! [`Pin`]`<&Self>` or [`Pin`]`<&mut Self>`) has consequences for your [`Drop`]
176 //! implementation as well: if an element of your type could have been pinned,
177 //! you must treat [`Drop`] as implicitly taking [`Pin`]`<&mut Self>`.
178 //!
179 //! For example, you could implement `Drop` as follows:
180 //!
181 //! ```rust,no_run
182 //! # use std::pin::Pin;
183 //! # struct Type { }
184 //! impl Drop for Type {
185 //!     fn drop(&mut self) {
186 //!         // `new_unchecked` is okay because we know this value is never used
187 //!         // again after being dropped.
188 //!         inner_drop(unsafe { Pin::new_unchecked(self)});
189 //!         fn inner_drop(this: Pin<&mut Type>) {
190 //!             // Actual drop code goes here.
191 //!         }
192 //!     }
193 //! }
194 //! ```
195 //!
196 //! The function `inner_drop` has the type that [`drop`] *should* have, so this makes sure that
197 //! you do not accidentally use `self`/`this` in a way that is in conflict with pinning.
198 //!
199 //! Moreover, if your type is `#[repr(packed)]`, the compiler will automatically
200 //! move fields around to be able to drop them. It might even do
201 //! that for fields that happen to be sufficiently aligned. As a consequence, you cannot use
202 //! pinning with a `#[repr(packed)]` type.
203 //!
204 //! # Projections and Structural Pinning
205 //!
206 //! When working with pinned structs, the question arises how one can access the
207 //! fields of that struct in a method that takes just [`Pin`]`<&mut Struct>`.
208 //! The usual approach is to write helper methods (so called *projections*)
209 //! that turn [`Pin`]`<&mut Struct>` into a reference to the field, but what
210 //! type should that reference have? Is it [`Pin`]`<&mut Field>` or `&mut Field`?
211 //! The same question arises with the fields of an `enum`, and also when considering
212 //! container/wrapper types such as [`Vec<T>`], [`Box<T>`], or [`RefCell<T>`].
213 //! (This question applies to both mutable and shared references, we just
214 //! use the more common case of mutable references here for illustration.)
215 //!
216 //! It turns out that it is actually up to the author of the data structure
217 //! to decide whether the pinned projection for a particular field turns
218 //! [`Pin`]`<&mut Struct>` into [`Pin`]`<&mut Field>` or `&mut Field`. There are some
219 //! constraints though, and the most important constraint is *consistency*:
220 //! every field can be *either* projected to a pinned reference, *or* have
221 //! pinning removed as part of the projection. If both are done for the same field,
222 //! that will likely be unsound!
223 //!
224 //! As the author of a data structure you get to decide for each field whether pinning
225 //! "propagates" to this field or not. Pinning that propagates is also called "structural",
226 //! because it follows the structure of the type.
227 //! In the following subsections, we describe the considerations that have to be made
228 //! for either choice.
229 //!
230 //! ## Pinning *is not* structural for `field`
231 //!
232 //! It may seem counter-intuitive that the field of a pinned struct might not be pinned,
233 //! but that is actually the easiest choice: if a [`Pin`]`<&mut Field>` is never created,
234 //! nothing can go wrong! So, if you decide that some field does not have structural pinning,
235 //! all you have to ensure is that you never create a pinned reference to that field.
236 //!
237 //! Fields without structural pinning may have a projection method that turns
238 //! [`Pin`]`<&mut Struct>` into `&mut Field`:
239 //!
240 //! ```rust,no_run
241 //! # use std::pin::Pin;
242 //! # type Field = i32;
243 //! # struct Struct { field: Field }
244 //! impl Struct {
245 //!     fn pin_get_field(self: Pin<&mut Self>) -> &mut Field {
246 //!         // This is okay because `field` is never considered pinned.
247 //!         unsafe { &mut self.get_unchecked_mut().field }
248 //!     }
249 //! }
250 //! ```
251 //!
252 //! You may also `impl Unpin for Struct` *even if* the type of `field`
253 //! is not [`Unpin`]. What that type thinks about pinning is not relevant
254 //! when no [`Pin`]`<&mut Field>` is ever created.
255 //!
256 //! ## Pinning *is* structural for `field`
257 //!
258 //! The other option is to decide that pinning is "structural" for `field`,
259 //! meaning that if the struct is pinned then so is the field.
260 //!
261 //! This allows writing a projection that creates a [`Pin`]`<&mut Field>`, thus
262 //! witnessing that the field is pinned:
263 //!
264 //! ```rust,no_run
265 //! # use std::pin::Pin;
266 //! # type Field = i32;
267 //! # struct Struct { field: Field }
268 //! impl Struct {
269 //!     fn pin_get_field(self: Pin<&mut Self>) -> Pin<&mut Field> {
270 //!         // This is okay because `field` is pinned when `self` is.
271 //!         unsafe { self.map_unchecked_mut(|s| &mut s.field) }
272 //!     }
273 //! }
274 //! ```
275 //!
276 //! However, structural pinning comes with a few extra requirements:
277 //!
278 //! 1.  The struct must only be [`Unpin`] if all the structural fields are
279 //!     [`Unpin`]. This is the default, but [`Unpin`] is a safe trait, so as the author of
280 //!     the struct it is your responsibility *not* to add something like
281 //!     `impl<T> Unpin for Struct<T>`. (Notice that adding a projection operation
282 //!     requires unsafe code, so the fact that [`Unpin`] is a safe trait does not break
283 //!     the principle that you only have to worry about any of this if you use `unsafe`.)
284 //! 2.  The destructor of the struct must not move structural fields out of its argument. This
285 //!     is the exact point that was raised in the [previous section][drop-impl]: `drop` takes
286 //!     `&mut self`, but the struct (and hence its fields) might have been pinned before.
287 //!     You have to guarantee that you do not move a field inside your [`Drop`] implementation.
288 //!     In particular, as explained previously, this means that your struct must *not*
289 //!     be `#[repr(packed)]`.
290 //!     See that section for how to write [`drop`] in a way that the compiler can help you
291 //!     not accidentally break pinning.
292 //! 3.  You must make sure that you uphold the [`Drop` guarantee][drop-guarantee]:
293 //!     once your struct is pinned, the memory that contains the
294 //!     content is not overwritten or deallocated without calling the content's destructors.
295 //!     This can be tricky, as witnessed by [`VecDeque<T>`]: the destructor of [`VecDeque<T>`]
296 //!     can fail to call [`drop`] on all elements if one of the destructors panics. This violates
297 //!     the [`Drop`] guarantee, because it can lead to elements being deallocated without
298 //!     their destructor being called. ([`VecDeque<T>`] has no pinning projections, so this
299 //!     does not cause unsoundness.)
300 //! 4.  You must not offer any other operations that could lead to data being moved out of
301 //!     the structural fields when your type is pinned. For example, if the struct contains an
302 //!     [`Option<T>`] and there is a `take`-like operation with type
303 //!     `fn(Pin<&mut Struct<T>>) -> Option<T>`,
304 //!     that operation can be used to move a `T` out of a pinned `Struct<T>` -- which means
305 //!     pinning cannot be structural for the field holding this data.
306 //!
307 //!     For a more complex example of moving data out of a pinned type, imagine if [`RefCell<T>`]
308 //!     had a method `fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>`.
309 //!     Then we could do the following:
310 //!     ```compile_fail
311 //!     fn exploit_ref_cell<T>(rc: Pin<&mut RefCell<T>>) {
312 //!         { let p = rc.as_mut().get_pin_mut(); } // Here we get pinned access to the `T`.
313 //!         let rc_shr: &RefCell<T> = rc.into_ref().get_ref();
314 //!         let b = rc_shr.borrow_mut();
315 //!         let content = &mut *b; // And here we have `&mut T` to the same data.
316 //!     }
317 //!     ```
318 //!     This is catastrophic, it means we can first pin the content of the [`RefCell<T>`]
319 //!     (using `RefCell::get_pin_mut`) and then move that content using the mutable
320 //!     reference we got later.
321 //!
322 //! ## Examples
323 //!
324 //! For a type like [`Vec<T>`], both possibilities (structural pinning or not) make sense.
325 //! A [`Vec<T>`] with structural pinning could have `get_pin`/`get_pin_mut` methods to get
326 //! pinned references to elements. However, it could *not* allow calling
327 //! [`pop`][Vec::pop] on a pinned [`Vec<T>`] because that would move the (structurally pinned)
328 //! contents! Nor could it allow [`push`][Vec::push], which might reallocate and thus also move the
329 //! contents.
330 //!
331 //! A [`Vec<T>`] without structural pinning could `impl<T> Unpin for Vec<T>`, because the contents
332 //! are never pinned and the [`Vec<T>`] itself is fine with being moved as well.
333 //! At that point pinning just has no effect on the vector at all.
334 //!
335 //! In the standard library, pointer types generally do not have structural pinning,
336 //! and thus they do not offer pinning projections. This is why `Box<T>: Unpin` holds for all `T`.
337 //! It makes sense to do this for pointer types, because moving the `Box<T>`
338 //! does not actually move the `T`: the [`Box<T>`] can be freely movable (aka `Unpin`) even if
339 //! the `T` is not. In fact, even [`Pin`]`<`[`Box`]`<T>>` and [`Pin`]`<&mut T>` are always
340 //! [`Unpin`] themselves, for the same reason: their contents (the `T`) are pinned, but the
341 //! pointers themselves can be moved without moving the pinned data. For both [`Box<T>`] and
342 //! [`Pin`]`<`[`Box`]`<T>>`, whether the content is pinned is entirely independent of whether the
343 //! pointer is pinned, meaning pinning is *not* structural.
344 //!
345 //! When implementing a [`Future`] combinator, you will usually need structural pinning
346 //! for the nested futures, as you need to get pinned references to them to call [`poll`].
347 //! But if your combinator contains any other data that does not need to be pinned,
348 //! you can make those fields not structural and hence freely access them with a
349 //! mutable reference even when you just have [`Pin`]`<&mut Self>` (such as in your own
350 //! [`poll`] implementation).
351 //!
352 //! [`Deref`]: crate::ops::Deref
353 //! [`DerefMut`]: crate::ops::DerefMut
354 //! [`mem::swap`]: crate::mem::swap
355 //! [`mem::forget`]: crate::mem::forget
356 //! [`Box<T>`]: ../../std/boxed/struct.Box.html
357 //! [`Vec<T>`]: ../../std/vec/struct.Vec.html
358 //! [`Vec::set_len`]: ../../std/vec/struct.Vec.html#method.set_len
359 //! [`Box`]: ../../std/boxed/struct.Box.html
360 //! [Vec::pop]: ../../std/vec/struct.Vec.html#method.pop
361 //! [Vec::push]: ../../std/vec/struct.Vec.html#method.push
362 //! [`Rc`]: ../../std/rc/struct.Rc.html
363 //! [`RefCell<T>`]: crate::cell::RefCell
364 //! [`drop`]: Drop::drop
365 //! [`VecDeque<T>`]: ../../std/collections/struct.VecDeque.html
366 //! [`Some(v)`]: Some
367 //! [`ptr::write`]: crate::ptr::write
368 //! [`Future`]: crate::future::Future
369 //! [drop-impl]: #drop-implementation
370 //! [drop-guarantee]: #drop-guarantee
371 //! [`poll`]: crate::future::Future::poll
372
373 #![stable(feature = "pin", since = "1.33.0")]
374
375 use crate::cmp::{self, PartialEq, PartialOrd};
376 use crate::fmt;
377 use crate::hash::{Hash, Hasher};
378 use crate::marker::{Sized, Unpin};
379 use crate::ops::{CoerceUnsized, Deref, DerefMut, DispatchFromDyn, Receiver};
380
381 /// A pinned pointer.
382 ///
383 /// This is a wrapper around a kind of pointer which makes that pointer "pin" its
384 /// value in place, preventing the value referenced by that pointer from being moved
385 /// unless it implements [`Unpin`].
386 ///
387 /// *See the [`pin` module] documentation for an explanation of pinning.*
388 ///
389 /// [`pin` module]: self
390 //
391 // Note: the `Clone` derive below causes unsoundness as it's possible to implement
392 // `Clone` for mutable references.
393 // See <https://internals.rust-lang.org/t/unsoundness-in-pin/11311> for more details.
394 #[stable(feature = "pin", since = "1.33.0")]
395 #[lang = "pin"]
396 #[fundamental]
397 #[repr(transparent)]
398 #[derive(Copy, Clone)]
399 pub struct Pin<P> {
400     pointer: P,
401 }
402
403 // The following implementations aren't derived in order to avoid soundness
404 // issues. `&self.pointer` should not be accessible to untrusted trait
405 // implementations.
406 //
407 // See <https://internals.rust-lang.org/t/unsoundness-in-pin/11311/73> for more details.
408
409 #[stable(feature = "pin_trait_impls", since = "1.41.0")]
410 impl<P: Deref, Q: Deref> PartialEq<Pin<Q>> for Pin<P>
411 where
412     P::Target: PartialEq<Q::Target>,
413 {
414     fn eq(&self, other: &Pin<Q>) -> bool {
415         P::Target::eq(self, other)
416     }
417
418     fn ne(&self, other: &Pin<Q>) -> bool {
419         P::Target::ne(self, other)
420     }
421 }
422
423 #[stable(feature = "pin_trait_impls", since = "1.41.0")]
424 impl<P: Deref<Target: Eq>> Eq for Pin<P> {}
425
426 #[stable(feature = "pin_trait_impls", since = "1.41.0")]
427 impl<P: Deref, Q: Deref> PartialOrd<Pin<Q>> for Pin<P>
428 where
429     P::Target: PartialOrd<Q::Target>,
430 {
431     fn partial_cmp(&self, other: &Pin<Q>) -> Option<cmp::Ordering> {
432         P::Target::partial_cmp(self, other)
433     }
434
435     fn lt(&self, other: &Pin<Q>) -> bool {
436         P::Target::lt(self, other)
437     }
438
439     fn le(&self, other: &Pin<Q>) -> bool {
440         P::Target::le(self, other)
441     }
442
443     fn gt(&self, other: &Pin<Q>) -> bool {
444         P::Target::gt(self, other)
445     }
446
447     fn ge(&self, other: &Pin<Q>) -> bool {
448         P::Target::ge(self, other)
449     }
450 }
451
452 #[stable(feature = "pin_trait_impls", since = "1.41.0")]
453 impl<P: Deref<Target: Ord>> Ord for Pin<P> {
454     fn cmp(&self, other: &Self) -> cmp::Ordering {
455         P::Target::cmp(self, other)
456     }
457 }
458
459 #[stable(feature = "pin_trait_impls", since = "1.41.0")]
460 impl<P: Deref<Target: Hash>> Hash for Pin<P> {
461     fn hash<H: Hasher>(&self, state: &mut H) {
462         P::Target::hash(self, state);
463     }
464 }
465
466 impl<P: Deref<Target: Unpin>> Pin<P> {
467     /// Construct a new `Pin<P>` around a pointer to some data of a type that
468     /// implements [`Unpin`].
469     ///
470     /// Unlike `Pin::new_unchecked`, this method is safe because the pointer
471     /// `P` dereferences to an [`Unpin`] type, which cancels the pinning guarantees.
472     #[inline(always)]
473     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
474     #[stable(feature = "pin", since = "1.33.0")]
475     pub const fn new(pointer: P) -> Pin<P> {
476         // SAFETY: the value pointed to is `Unpin`, and so has no requirements
477         // around pinning.
478         unsafe { Pin::new_unchecked(pointer) }
479     }
480
481     /// Unwraps this `Pin<P>` returning the underlying pointer.
482     ///
483     /// This requires that the data inside this `Pin` is [`Unpin`] so that we
484     /// can ignore the pinning invariants when unwrapping it.
485     #[inline(always)]
486     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
487     #[stable(feature = "pin_into_inner", since = "1.39.0")]
488     pub const fn into_inner(pin: Pin<P>) -> P {
489         pin.pointer
490     }
491 }
492
493 impl<P: Deref> Pin<P> {
494     /// Construct a new `Pin<P>` around a reference to some data of a type that
495     /// may or may not implement `Unpin`.
496     ///
497     /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
498     /// instead.
499     ///
500     /// # Safety
501     ///
502     /// This constructor is unsafe because we cannot guarantee that the data
503     /// pointed to by `pointer` is pinned, meaning that the data will not be moved or
504     /// its storage invalidated until it gets dropped. If the constructed `Pin<P>` does
505     /// not guarantee that the data `P` points to is pinned, that is a violation of
506     /// the API contract and may lead to undefined behavior in later (safe) operations.
507     ///
508     /// By using this method, you are making a promise about the `P::Deref` and
509     /// `P::DerefMut` implementations, if they exist. Most importantly, they
510     /// must not move out of their `self` arguments: `Pin::as_mut` and `Pin::as_ref`
511     /// will call `DerefMut::deref_mut` and `Deref::deref` *on the pinned pointer*
512     /// and expect these methods to uphold the pinning invariants.
513     /// Moreover, by calling this method you promise that the reference `P`
514     /// dereferences to will not be moved out of again; in particular, it
515     /// must not be possible to obtain a `&mut P::Target` and then
516     /// move out of that reference (using, for example [`mem::swap`]).
517     ///
518     /// For example, calling `Pin::new_unchecked` on an `&'a mut T` is unsafe because
519     /// while you are able to pin it for the given lifetime `'a`, you have no control
520     /// over whether it is kept pinned once `'a` ends:
521     /// ```
522     /// use std::mem;
523     /// use std::pin::Pin;
524     ///
525     /// fn move_pinned_ref<T>(mut a: T, mut b: T) {
526     ///     unsafe {
527     ///         let p: Pin<&mut T> = Pin::new_unchecked(&mut a);
528     ///         // This should mean the pointee `a` can never move again.
529     ///     }
530     ///     mem::swap(&mut a, &mut b);
531     ///     // The address of `a` changed to `b`'s stack slot, so `a` got moved even
532     ///     // though we have previously pinned it! We have violated the pinning API contract.
533     /// }
534     /// ```
535     /// A value, once pinned, must remain pinned forever (unless its type implements `Unpin`).
536     ///
537     /// Similarly, calling `Pin::new_unchecked` on an `Rc<T>` is unsafe because there could be
538     /// aliases to the same data that are not subject to the pinning restrictions:
539     /// ```
540     /// use std::rc::Rc;
541     /// use std::pin::Pin;
542     ///
543     /// fn move_pinned_rc<T>(mut x: Rc<T>) {
544     ///     let pinned = unsafe { Pin::new_unchecked(Rc::clone(&x)) };
545     ///     {
546     ///         let p: Pin<&T> = pinned.as_ref();
547     ///         // This should mean the pointee can never move again.
548     ///     }
549     ///     drop(pinned);
550     ///     let content = Rc::get_mut(&mut x).unwrap();
551     ///     // Now, if `x` was the only reference, we have a mutable reference to
552     ///     // data that we pinned above, which we could use to move it as we have
553     ///     // seen in the previous example. We have violated the pinning API contract.
554     ///  }
555     ///  ```
556     ///
557     /// [`mem::swap`]: crate::mem::swap
558     #[lang = "new_unchecked"]
559     #[inline(always)]
560     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
561     #[stable(feature = "pin", since = "1.33.0")]
562     pub const unsafe fn new_unchecked(pointer: P) -> Pin<P> {
563         Pin { pointer }
564     }
565
566     /// Gets a pinned shared reference from this pinned pointer.
567     ///
568     /// This is a generic method to go from `&Pin<Pointer<T>>` to `Pin<&T>`.
569     /// It is safe because, as part of the contract of `Pin::new_unchecked`,
570     /// the pointee cannot move after `Pin<Pointer<T>>` got created.
571     /// "Malicious" implementations of `Pointer::Deref` are likewise
572     /// ruled out by the contract of `Pin::new_unchecked`.
573     #[stable(feature = "pin", since = "1.33.0")]
574     #[inline(always)]
575     pub fn as_ref(&self) -> Pin<&P::Target> {
576         // SAFETY: see documentation on this function
577         unsafe { Pin::new_unchecked(&*self.pointer) }
578     }
579
580     /// Unwraps this `Pin<P>` returning the underlying pointer.
581     ///
582     /// # Safety
583     ///
584     /// This function is unsafe. You must guarantee that you will continue to
585     /// treat the pointer `P` as pinned after you call this function, so that
586     /// the invariants on the `Pin` type can be upheld. If the code using the
587     /// resulting `P` does not continue to maintain the pinning invariants that
588     /// is a violation of the API contract and may lead to undefined behavior in
589     /// later (safe) operations.
590     ///
591     /// If the underlying data is [`Unpin`], [`Pin::into_inner`] should be used
592     /// instead.
593     #[inline(always)]
594     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
595     #[stable(feature = "pin_into_inner", since = "1.39.0")]
596     pub const unsafe fn into_inner_unchecked(pin: Pin<P>) -> P {
597         pin.pointer
598     }
599 }
600
601 impl<P: DerefMut> Pin<P> {
602     /// Gets a pinned mutable reference from this pinned pointer.
603     ///
604     /// This is a generic method to go from `&mut Pin<Pointer<T>>` to `Pin<&mut T>`.
605     /// It is safe because, as part of the contract of `Pin::new_unchecked`,
606     /// the pointee cannot move after `Pin<Pointer<T>>` got created.
607     /// "Malicious" implementations of `Pointer::DerefMut` are likewise
608     /// ruled out by the contract of `Pin::new_unchecked`.
609     ///
610     /// This method is useful when doing multiple calls to functions that consume the pinned type.
611     ///
612     /// # Example
613     ///
614     /// ```
615     /// use std::pin::Pin;
616     ///
617     /// # struct Type {}
618     /// impl Type {
619     ///     fn method(self: Pin<&mut Self>) {
620     ///         // do something
621     ///     }
622     ///
623     ///     fn call_method_twice(mut self: Pin<&mut Self>) {
624     ///         // `method` consumes `self`, so reborrow the `Pin<&mut Self>` via `as_mut`.
625     ///         self.as_mut().method();
626     ///         self.as_mut().method();
627     ///     }
628     /// }
629     /// ```
630     #[stable(feature = "pin", since = "1.33.0")]
631     #[inline(always)]
632     pub fn as_mut(&mut self) -> Pin<&mut P::Target> {
633         // SAFETY: see documentation on this function
634         unsafe { Pin::new_unchecked(&mut *self.pointer) }
635     }
636
637     /// Assigns a new value to the memory behind the pinned reference.
638     ///
639     /// This overwrites pinned data, but that is okay: its destructor gets
640     /// run before being overwritten, so no pinning guarantee is violated.
641     #[stable(feature = "pin", since = "1.33.0")]
642     #[inline(always)]
643     pub fn set(&mut self, value: P::Target)
644     where
645         P::Target: Sized,
646     {
647         *(self.pointer) = value;
648     }
649 }
650
651 impl<'a, T: ?Sized> Pin<&'a T> {
652     /// Constructs a new pin by mapping the interior value.
653     ///
654     /// For example, if you  wanted to get a `Pin` of a field of something,
655     /// you could use this to get access to that field in one line of code.
656     /// However, there are several gotchas with these "pinning projections";
657     /// see the [`pin` module] documentation for further details on that topic.
658     ///
659     /// # Safety
660     ///
661     /// This function is unsafe. You must guarantee that the data you return
662     /// will not move so long as the argument value does not move (for example,
663     /// because it is one of the fields of that value), and also that you do
664     /// not move out of the argument you receive to the interior function.
665     ///
666     /// [`pin` module]: self#projections-and-structural-pinning
667     #[stable(feature = "pin", since = "1.33.0")]
668     pub unsafe fn map_unchecked<U, F>(self, func: F) -> Pin<&'a U>
669     where
670         U: ?Sized,
671         F: FnOnce(&T) -> &U,
672     {
673         let pointer = &*self.pointer;
674         let new_pointer = func(pointer);
675
676         // SAFETY: the safety contract for `new_unchecked` must be
677         // upheld by the caller.
678         unsafe { Pin::new_unchecked(new_pointer) }
679     }
680
681     /// Gets a shared reference out of a pin.
682     ///
683     /// This is safe because it is not possible to move out of a shared reference.
684     /// It may seem like there is an issue here with interior mutability: in fact,
685     /// it *is* possible to move a `T` out of a `&RefCell<T>`. However, this is
686     /// not a problem as long as there does not also exist a `Pin<&T>` pointing
687     /// to the same data, and `RefCell<T>` does not let you create a pinned reference
688     /// to its contents. See the discussion on ["pinning projections"] for further
689     /// details.
690     ///
691     /// Note: `Pin` also implements `Deref` to the target, which can be used
692     /// to access the inner value. However, `Deref` only provides a reference
693     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
694     /// the `Pin` itself. This method allows turning the `Pin` into a reference
695     /// with the same lifetime as the original `Pin`.
696     ///
697     /// ["pinning projections"]: self#projections-and-structural-pinning
698     #[inline(always)]
699     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
700     #[stable(feature = "pin", since = "1.33.0")]
701     pub const fn get_ref(self) -> &'a T {
702         self.pointer
703     }
704 }
705
706 impl<'a, T: ?Sized> Pin<&'a mut T> {
707     /// Converts this `Pin<&mut T>` into a `Pin<&T>` with the same lifetime.
708     #[inline(always)]
709     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
710     #[stable(feature = "pin", since = "1.33.0")]
711     pub const fn into_ref(self) -> Pin<&'a T> {
712         Pin { pointer: self.pointer }
713     }
714
715     /// Gets a mutable reference to the data inside of this `Pin`.
716     ///
717     /// This requires that the data inside this `Pin` is `Unpin`.
718     ///
719     /// Note: `Pin` also implements `DerefMut` to the data, which can be used
720     /// to access the inner value. However, `DerefMut` only provides a reference
721     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
722     /// the `Pin` itself. This method allows turning the `Pin` into a reference
723     /// with the same lifetime as the original `Pin`.
724     #[inline(always)]
725     #[stable(feature = "pin", since = "1.33.0")]
726     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
727     pub const fn get_mut(self) -> &'a mut T
728     where
729         T: Unpin,
730     {
731         self.pointer
732     }
733
734     /// Gets a mutable reference to the data inside of this `Pin`.
735     ///
736     /// # Safety
737     ///
738     /// This function is unsafe. You must guarantee that you will never move
739     /// the data out of the mutable reference you receive when you call this
740     /// function, so that the invariants on the `Pin` type can be upheld.
741     ///
742     /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
743     /// instead.
744     #[inline(always)]
745     #[stable(feature = "pin", since = "1.33.0")]
746     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
747     pub const unsafe fn get_unchecked_mut(self) -> &'a mut T {
748         self.pointer
749     }
750
751     /// Construct a new pin by mapping the interior value.
752     ///
753     /// For example, if you  wanted to get a `Pin` of a field of something,
754     /// you could use this to get access to that field in one line of code.
755     /// However, there are several gotchas with these "pinning projections";
756     /// see the [`pin` module] documentation for further details on that topic.
757     ///
758     /// # Safety
759     ///
760     /// This function is unsafe. You must guarantee that the data you return
761     /// will not move so long as the argument value does not move (for example,
762     /// because it is one of the fields of that value), and also that you do
763     /// not move out of the argument you receive to the interior function.
764     ///
765     /// [`pin` module]: self#projections-and-structural-pinning
766     #[stable(feature = "pin", since = "1.33.0")]
767     pub unsafe fn map_unchecked_mut<U, F>(self, func: F) -> Pin<&'a mut U>
768     where
769         U: ?Sized,
770         F: FnOnce(&mut T) -> &mut U,
771     {
772         // SAFETY: the caller is responsible for not moving the
773         // value out of this reference.
774         let pointer = unsafe { Pin::get_unchecked_mut(self) };
775         let new_pointer = func(pointer);
776         // SAFETY: as the value of `this` is guaranteed to not have
777         // been moved out, this call to `new_unchecked` is safe.
778         unsafe { Pin::new_unchecked(new_pointer) }
779     }
780 }
781
782 impl<T: ?Sized> Pin<&'static T> {
783     /// Get a pinned reference from a static reference.
784     ///
785     /// This is safe, because `T` is borrowed for the `'static` lifetime, which
786     /// never ends.
787     #[unstable(feature = "pin_static_ref", issue = "78186")]
788     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
789     pub const fn static_ref(r: &'static T) -> Pin<&'static T> {
790         // SAFETY: The 'static borrow guarantees the data will not be
791         // moved/invalidated until it gets dropped (which is never).
792         unsafe { Pin::new_unchecked(r) }
793     }
794 }
795
796 impl<T: ?Sized> Pin<&'static mut T> {
797     /// Get a pinned mutable reference from a static mutable reference.
798     ///
799     /// This is safe, because `T` is borrowed for the `'static` lifetime, which
800     /// never ends.
801     #[unstable(feature = "pin_static_ref", issue = "78186")]
802     #[rustc_const_unstable(feature = "const_pin", issue = "76654")]
803     pub const fn static_mut(r: &'static mut T) -> Pin<&'static mut T> {
804         // SAFETY: The 'static borrow guarantees the data will not be
805         // moved/invalidated until it gets dropped (which is never).
806         unsafe { Pin::new_unchecked(r) }
807     }
808 }
809
810 #[stable(feature = "pin", since = "1.33.0")]
811 impl<P: Deref> Deref for Pin<P> {
812     type Target = P::Target;
813     fn deref(&self) -> &P::Target {
814         Pin::get_ref(Pin::as_ref(self))
815     }
816 }
817
818 #[stable(feature = "pin", since = "1.33.0")]
819 impl<P: DerefMut<Target: Unpin>> DerefMut for Pin<P> {
820     fn deref_mut(&mut self) -> &mut P::Target {
821         Pin::get_mut(Pin::as_mut(self))
822     }
823 }
824
825 #[unstable(feature = "receiver_trait", issue = "none")]
826 impl<P: Receiver> Receiver for Pin<P> {}
827
828 #[stable(feature = "pin", since = "1.33.0")]
829 impl<P: fmt::Debug> fmt::Debug for Pin<P> {
830     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
831         fmt::Debug::fmt(&self.pointer, f)
832     }
833 }
834
835 #[stable(feature = "pin", since = "1.33.0")]
836 impl<P: fmt::Display> fmt::Display for Pin<P> {
837     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
838         fmt::Display::fmt(&self.pointer, f)
839     }
840 }
841
842 #[stable(feature = "pin", since = "1.33.0")]
843 impl<P: fmt::Pointer> fmt::Pointer for Pin<P> {
844     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
845         fmt::Pointer::fmt(&self.pointer, f)
846     }
847 }
848
849 // Note: this means that any impl of `CoerceUnsized` that allows coercing from
850 // a type that impls `Deref<Target=impl !Unpin>` to a type that impls
851 // `Deref<Target=Unpin>` is unsound. Any such impl would probably be unsound
852 // for other reasons, though, so we just need to take care not to allow such
853 // impls to land in std.
854 #[stable(feature = "pin", since = "1.33.0")]
855 impl<P, U> CoerceUnsized<Pin<U>> for Pin<P> where P: CoerceUnsized<U> {}
856
857 #[stable(feature = "pin", since = "1.33.0")]
858 impl<P, U> DispatchFromDyn<Pin<U>> for Pin<P> where P: DispatchFromDyn<U> {}