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