]> git.lizzy.rs Git - rust.git/blob - src/libcore/pin.rs
5056005bcd773ecddcbcff42f9d3eb288f82cd11
[rust.git] / src / libcore / pin.rs
1 //! Types which pin data to its location in memory
2 //!
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.
5 //! A prime example of such a scenario would be building self-referential structs,
6 //! since moving an object with pointers to itself will invalidate them,
7 //! which could cause undefined behavior.
8 //!
9 //! [`Pin`] ensures that the pointee of any pointer type 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` and `&mut` allow replacing and
15 //! moving the values they contain: you can move out of a `Box`, or you can use [`mem::swap`].
16 //! [`Pin`] wraps a pointer type, so `Pin<Box<T>>` functions much like a regular `Box<T>`
17 //! (when a `Pin<Box<T>>` gets dropped, so do its contents, and the memory gets deallocated).
18 //! Similarily, `Pin<&mut T>` is a lot like `&mut T`. However, [`Pin`] does not let clients actually
19 //! obtain a `Box` or reference to pinned data, which implies that you cannot use
20 //! operations such as [`mem::swap`]:
21 //! ```
22 //! use std::pin::Pin;
23 //! fn swap_pins<T>(x: Pin<&mut T>, y: Pin<&mut T>) {
24 //!     // `mem::swap` needs `&mut T`, but we cannot get it.
25 //!     // We are stuck, we cannot swap the contents of these references.
26 //!     // We could use `Pin::get_unchecked_mut`, but that is unsafe for a reason:
27 //!     // we are not allowed to use it for moving things out of the `Pin`.
28 //! }
29 //! ```
30 //!
31 //! It is worth reiterating that [`Pin`] does *not* change the fact that a Rust compiler
32 //! considers all types movable.  [`mem::swap`] remains callable for any `T`. Instead, `Pin`
33 //! prevents certain *values* (pointed to by pointers wrapped in `Pin`) from being
34 //! moved by making it impossible to call methods like [`mem::swap`] on them.
35 //!
36 //! [`Pin`] can be used to wrap any pointer type, and as such it interacts with
37 //! [`Deref`] and [`DerefMut`]. A `Pin<P>` where `P: Deref` should be considered
38 //! as a "`P`-style pointer" to a pinned `P::Target` -- so, a `Pin<Box<T>>` is
39 //! an owned pointer to a pinned `T`, and a `Pin<Rc<T>>` is a reference-counted
40 //! pointer to a pinned `T`.
41 //! For correctness, [`Pin`] relies on the [`Deref`] and [`DerefMut`] implementations
42 //! to not move out of their `self` parameter, and to only ever return a pointer
43 //! to pinned data when they are called on a pinned pointer.
44 //!
45 //! # `Unpin`
46 //!
47 //! However, these restrictions are usually not necessary. Many types are always freely
48 //! movable, even when pinned, because they do not rely on having a stable address.
49 //! This includes all the basic types (`bool`, `i32` and friends, references)
50 //! as well as types consisting solely of these types.
51 //! Types that do not care about pinning implement the [`Unpin`] auto-trait, which
52 //! nullifies the effect of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function
53 //! identically, as do `Pin<&mut T>` and `&mut T`.
54 //!
55 //! Note that pinning and `Unpin` only affect the pointed-to type, not the pointer
56 //! type itself that got wrapped in `Pin`. For example, whether or not `Box<T>` is
57 //! `Unpin` has no effect on the behavior of `Pin<Box<T>>` (here, `T` is the
58 //! pointed-to type).
59 //!
60 //! # Example: self-referential struct
61 //!
62 //! ```rust
63 //! use std::pin::Pin;
64 //! use std::marker::PhantomPinned;
65 //! use std::ptr::NonNull;
66 //!
67 //! // This is a self-referential struct since the slice field points to the data field.
68 //! // We cannot inform the compiler about that with a normal reference,
69 //! // since this pattern cannot be described with the usual borrowing rules.
70 //! // Instead we use a raw pointer, though one which is known to not be null,
71 //! // since we know it's pointing at the string.
72 //! struct Unmovable {
73 //!     data: String,
74 //!     slice: NonNull<String>,
75 //!     _pin: PhantomPinned,
76 //! }
77 //!
78 //! impl Unmovable {
79 //!     // To ensure the data doesn't move when the function returns,
80 //!     // we place it in the heap where it will stay for the lifetime of the object,
81 //!     // and the only way to access it would be through a pointer to it.
82 //!     fn new(data: String) -> Pin<Box<Self>> {
83 //!         let res = Unmovable {
84 //!             data,
85 //!             // we only create the pointer once the data is in place
86 //!             // otherwise it will have already moved before we even started
87 //!             slice: NonNull::dangling(),
88 //!             _pin: PhantomPinned,
89 //!         };
90 //!         let mut boxed = Box::pin(res);
91 //!
92 //!         let slice = NonNull::from(&boxed.data);
93 //!         // we know this is safe because modifying a field doesn't move the whole struct
94 //!         unsafe {
95 //!             let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
96 //!             Pin::get_unchecked_mut(mut_ref).slice = slice;
97 //!         }
98 //!         boxed
99 //!     }
100 //! }
101 //!
102 //! let unmoved = Unmovable::new("hello".to_string());
103 //! // The pointer should point to the correct location,
104 //! // so long as the struct hasn't moved.
105 //! // Meanwhile, we are free to move the pointer around.
106 //! # #[allow(unused_mut)]
107 //! let mut still_unmoved = unmoved;
108 //! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
109 //!
110 //! // Since our type doesn't implement Unpin, this will fail to compile:
111 //! // let new_unmoved = Unmovable::new("world".to_string());
112 //! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
113 //! ```
114 //!
115 //! # Example: intrusive doubly-linked list
116 //!
117 //! In an intrusive doubly-linked list, the collection does not actually allocate
118 //! the memory for the elements itself. Allocation is controlled by the clients,
119 //! and elements can live on a stack frame that lives shorter than the collection does.
120 //!
121 //! To make this work, every element has pointers to its predecessor and successor in
122 //! the list. Element can only be added when they are pinned, because moving the elements
123 //! around would invalidate the pointers. Moreover, the `Drop` implementation of a linked
124 //! list element will patch the pointers of its predecessor and successor to remove itself
125 //! from the list.
126 //!
127 //! To make this work, it is crucial that we can actually rely on `drop` being called.
128 //! And, in fact, this is a guarantee that `Pin` provides.
129 //!
130 //! # `Drop` guarantee
131 //!
132 //! The purpose of pinning is to be able to rely on the placement of some data in memory.
133 //! To make this work, not just moving the data is restricted; deallocating, repurposing or
134 //! otherwise invalidating the memory used to store the data is restricted, too.
135 //! Concretely, for pinned data you have to maintain the invariant
136 //! that *its memory will not get invalidated from the moment it gets pinned until
137 //! when `drop` is called*. Memory can be invalidated by deallocation, but also by
138 //! replacing a `Some(v)` by `None`, or calling `Vec::set_len` to "kill" some elements
139 //! off of a vector.
140 //!
141 //! This is exactly the kind of guarantee that the intrusive linked list from the previous
142 //! section needs to function correctly. Clearly, if an element
143 //! could be deallocated or otherwise invalidated without calling `drop`, the pointers into it
144 //! from its neighbouring elements would become invalid, which would break the data structure.
145 //!
146 //! Notice that this guarantee does *not* mean that memory does not leak! It is still
147 //! completely okay not to ever call `drop` on a pinned element (e.g., you can still
148 //! call [`mem::forget`] on a `Pin<Box<T>>`). In the example of the doubly-linked
149 //! list, that element would just stay in the list. However you may not free or reuse the storage
150 //! *without calling `drop`*.
151 //!
152 //! # `Drop` implementation
153 //!
154 //! If your type uses pinning (such as the two examples above), you have to be careful
155 //! when implementing `Drop`. The `drop` function takes `&mut self`, but this
156 //! is called *even if your type was previously pinned*! It is as if the
157 //! compiler automatically called `get_unchecked_mut`.
158 //!
159 //! This can never cause a problem in safe code because implementing a type that relies on pinning
160 //! requires unsafe code, but be aware that deciding to make use of pinning
161 //! in your type (for example by implementing some operation on `Pin<&[mut] Self>`)
162 //! has consequences for your `Drop` implementation as well: if an element
163 //! of your type could have been pinned, you must treat Drop as implicitly taking
164 //! `Pin<&mut Self>`.
165 //!
166 //! In particular, if your type is `#[repr(packed)]`, the compiler will automatically
167 //! move fields around to be able to drop them. As a consequence, you cannot use
168 //! pinning with a `#[repr(packed)]` type.
169 //!
170 //! # Projections and Structural Pinning
171 //!
172 //! One interesting question arises when considering the interaction of pinning and
173 //! the fields of a struct. When can a struct have a "pinning projection", i.e.,
174 //! an operation with type `fn(Pin<&[mut] Struct>) -> Pin<&[mut] Field>`?
175 //! In a similar vein, when can a container type (such as `Vec`, `Box`, or `RefCell`)
176 //! have an operation with type `fn(Pin<&[mut] Container<T>>) -> Pin<&[mut] T>`?
177 //!
178 //! This question is closely related to the question of whether pinning is "structural":
179 //! when you have pinned a wrapper type, have you pinned its contents? Deciding this
180 //! is entirely up to the author of any given type. However, adding a
181 //! projection to the API answers that question with a "yes" by offering pinned access
182 //! to the contents. In that case, there are a couple requirements to be upheld:
183 //!
184 //! 1. The wrapper must only be [`Unpin`] if all the fields one can project to are
185 //!    `Unpin`. This is the default, but `Unpin` is a safe trait, so as the author of
186 //!    the wrapper it is your responsibility *not* to add something like
187 //!    `impl<T> Unpin for Container<T>`. (Notice that adding a projection operation
188 //!    requires unsafe code, so the fact that `Unpin` is a safe trait  does not break
189 //!    the principle that you only have to worry about any of this if you use `unsafe`.)
190 //! 2. The destructor of the wrapper must not move out of its argument. This is the exact
191 //!    point that was raised in the [previous section][drop-impl]: `drop` takes `&mut self`,
192 //!    but the wrapper (and hence its fields) might have been pinned before.
193 //!    You have to guarantee that you do not move a field inside your `Drop` implementation.
194 //! 3. Your wrapper type must *not* be `#[repr(packed)]`. Packed structs have their fields
195 //!    moved around when they are dropped to properly align them, which is in conflict with
196 //!    claiming that the fields are pinned when your struct is.
197 //! 4. You must make sure that you uphold the [`Drop` guarantee][drop-guarantee]:
198 //!    once your wrapper is pinned, the memory that contains the
199 //!    content is not overwritten or deallocated without calling the content's destructors.
200 //!    This can be tricky, as witnessed by `VecDeque`: the destructor of `VecDeque` can fail
201 //!    to call `drop` on all elements if one of the destructors panics. This violates the
202 //!    `Drop` guarantee, because it can lead to elements being deallocated without
203 //!    their destructor being called. (`VecDeque` has no pinning projections, so this
204 //!    does not cause unsoundness.)
205 //! 5. You must not offer any other operations that could lead to data being moved out of
206 //!    the fields when your type is pinned. This is usually not a concern, but can become
207 //!    tricky when interior mutability is involved. For example, imagine `RefCell`
208 //!    would have a method `fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>`.
209 //!    Then we could do the following:
210 //!    ```compile_fail
211 //!    fn exploit_ref_cell<T>(rc: Pin<&mut RefCell<T>) {
212 //!        { let p = rc.as_mut().get_pin_mut(); } // here we get pinned access to the `T`
213 //!        let rc_shr: &RefCell<T> = rc.into_ref().get_ref();
214 //!        let b = rc_shr.borrow_mut();
215 //!        let content = &mut *b; // and here we have `&mut T` to the same data
216 //!    }
217 //!    ```
218 //!    This is catastrophic, it means we can first pin the content of the `RefCell`
219 //!    (using `RefCell::get_pin_mut`) and then move that content using the mutable
220 //!    reference we got later.
221 //!
222 //! On the other hand, if you decide *not* to offer any pinning projections, you
223 //! are free to `impl<T> Unpin for Container<T>`.  In the standard library,
224 //! this is done for all pointer types: `Box<T>: Unpin` holds for all `T`.
225 //! It makes sense to do this for pointer types, because moving the `Box<T>`
226 //! does not actually move the `T`: the `Box<T>` can be freely movable even if the `T`
227 //! is not. In fact, even `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves,
228 //! for the same reason.
229 //!
230 //! [`Pin`]: struct.Pin.html
231 //! [`Unpin`]: ../../std/marker/trait.Unpin.html
232 //! [`Deref`]: ../../std/ops/trait.Deref.html
233 //! [`DerefMut`]: ../../std/ops/trait.DerefMut.html
234 //! [`mem::swap`]: ../../std/mem/fn.swap.html
235 //! [`mem::forget`]: ../../std/mem/fn.forget.html
236 //! [`Box`]: ../../std/boxed/struct.Box.html
237 //! [drop-impl]: #drop-implementation
238 //! [drop-guarantee]: #drop-guarantee
239
240 #![stable(feature = "pin", since = "1.33.0")]
241
242 use fmt;
243 use marker::{Sized, Unpin};
244 use cmp::{self, PartialEq, PartialOrd};
245 use ops::{Deref, DerefMut, Receiver, CoerceUnsized, DispatchFromDyn};
246
247 /// A pinned pointer.
248 ///
249 /// This is a wrapper around a kind of pointer which makes that pointer "pin" its
250 /// value in place, preventing the value referenced by that pointer from being moved
251 /// unless it implements [`Unpin`].
252 ///
253 /// See the [`pin` module] documentation for further explanation on pinning.
254 ///
255 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
256 /// [`pin` module]: ../../std/pin/index.html
257 //
258 // Note: the derives below, and the explicit `PartialEq` and `PartialOrd`
259 // implementations, are allowed because they all only use `&P`, so they cannot move
260 // the value behind `pointer`.
261 #[stable(feature = "pin", since = "1.33.0")]
262 #[cfg_attr(not(stage0), lang = "pin")]
263 #[fundamental]
264 #[repr(transparent)]
265 #[derive(Copy, Clone, Hash, Eq, Ord)]
266 pub struct Pin<P> {
267     pointer: P,
268 }
269
270 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
271 impl<P, Q> PartialEq<Pin<Q>> for Pin<P>
272 where
273     P: PartialEq<Q>,
274 {
275     fn eq(&self, other: &Pin<Q>) -> bool {
276         self.pointer == other.pointer
277     }
278
279     fn ne(&self, other: &Pin<Q>) -> bool {
280         self.pointer != other.pointer
281     }
282 }
283
284 #[stable(feature = "pin_partialeq_partialord_impl_applicability", since = "1.34.0")]
285 impl<P, Q> PartialOrd<Pin<Q>> for Pin<P>
286 where
287     P: PartialOrd<Q>,
288 {
289     fn partial_cmp(&self, other: &Pin<Q>) -> Option<cmp::Ordering> {
290         self.pointer.partial_cmp(&other.pointer)
291     }
292
293     fn lt(&self, other: &Pin<Q>) -> bool {
294         self.pointer < other.pointer
295     }
296
297     fn le(&self, other: &Pin<Q>) -> bool {
298         self.pointer <= other.pointer
299     }
300
301     fn gt(&self, other: &Pin<Q>) -> bool {
302         self.pointer > other.pointer
303     }
304
305     fn ge(&self, other: &Pin<Q>) -> bool {
306         self.pointer >= other.pointer
307     }
308 }
309
310 impl<P: Deref> Pin<P>
311 where
312     P::Target: Unpin,
313 {
314     /// Construct a new `Pin` around a pointer to some data of a type that
315     /// implements [`Unpin`].
316     ///
317     /// Unlike `Pin::new_unchecked`, this method is safe because the pointer
318     /// `P` dereferences to an [`Unpin`] type, which nullifies the pinning guarantees.
319     ///
320     /// [`Unpin`]: ../../std/marker/trait.Unpin.html
321     #[stable(feature = "pin", since = "1.33.0")]
322     #[inline(always)]
323     pub fn new(pointer: P) -> Pin<P> {
324         // Safety: the value pointed to is `Unpin`, and so has no requirements
325         // around pinning.
326         unsafe { Pin::new_unchecked(pointer) }
327     }
328 }
329
330 impl<P: Deref> Pin<P> {
331     /// Construct a new `Pin` around a reference to some data of a type that
332     /// may or may not implement `Unpin`.
333     ///
334     /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
335     /// instead.
336     ///
337     /// # Safety
338     ///
339     /// This constructor is unsafe because we cannot guarantee that the data
340     /// pointed to by `pointer` is pinned, meaning that the data will not be moved or
341     /// its storage invalidated until it gets dropped. If the constructed `Pin<P>` does
342     /// not guarantee that the data `P` points to is pinned, constructing a
343     /// `Pin<P>` is unsafe. In particular,
344     ///
345     /// By using this method, you are making a promise about the `P::Deref` and
346     /// `P::DerefMut` implementations, if they exist. Most importantly, they
347     /// must not move out of their `self` arguments: `Pin::as_mut` and `Pin::as_ref`
348     /// will call `DerefMut::deref_mut` and `Deref::deref` *on the pinned pointer*
349     /// and expect these methods to uphold the pinning invariants.
350     /// Moreover, by calling this method you promise that the reference `P`
351     /// dereferences to will not be moved out of again; in particular, it
352     /// must not be possible to obtain a `&mut P::Target` and then
353     /// move out of that reference (using, for example [`mem::swap`]).
354     ///
355     /// For example, calling `Pin::new_unchecked`
356     /// on an `&'a mut T` is unsafe because while you are able to pin it for the given
357     /// lifetime `'a`, you have no control over whether it is kept pinned once `'a` ends:
358     /// ```
359     /// use std::mem;
360     /// use std::pin::Pin;
361     ///
362     /// fn move_pinned_ref<T>(mut a: T, mut b: T) {
363     ///     unsafe { let p = Pin::new_unchecked(&mut a); } // should mean `a` can never move again
364     ///     mem::swap(&mut a, &mut b);
365     ///     // the address of `a` changed to `b`'s stack slot, so `a` got moved even
366     ///     // though we have previously pinned it!
367     /// }
368     /// ```
369     /// A value, once pinned, must remain pinned forever (unless its type implements `Unpin`).
370     ///
371     /// Similarily, calling `Pin::new_unchecked` on a `Rc<T>` is unsafe because there could be
372     /// aliases to the same data that are not subject to the pinning restrictions:
373     /// ```
374     /// use std::rc::Rc;
375     /// use std::pin::Pin;
376     ///
377     /// fn move_pinned_rc<T>(mut x: Rc<T>) {
378     ///     let pinned = unsafe { Pin::new_unchecked(x.clone()) };
379     ///     { let p: Pin<&T> = pinned.as_ref(); } // should mean the pointee can never move again
380     ///     drop(pinned);
381     ///     let content = Rc::get_mut(&mut x).unwrap();
382     ///     // Now, if `x` was the only reference, we have a mutable reference to
383     ///     // data that we pinned above, which we could use to move it as we have
384     ///     // seen in the previous example.
385     ///  }
386     ///  ```
387     ///
388     /// [`mem::swap`]: ../../std/mem/fn.swap.html
389     #[stable(feature = "pin", since = "1.33.0")]
390     #[inline(always)]
391     pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
392         Pin { pointer }
393     }
394
395     /// Gets a pinned shared reference from this pinned pointer.
396     ///
397     /// This is a generic method to go from `&Pin<SmartPointer<T>>` to `Pin<&T>`.
398     /// It is safe because, as part of the contract of `Pin::new_unchecked`,
399     /// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
400     /// "Malicious" implementations of `SmartPointer::Deref` are likewise
401     /// ruled out by the contract of `Pin::new_unchecked`.
402     #[stable(feature = "pin", since = "1.33.0")]
403     #[inline(always)]
404     pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
405         unsafe { Pin::new_unchecked(&*self.pointer) }
406     }
407 }
408
409 impl<P: DerefMut> Pin<P> {
410     /// Gets a pinned mutable reference from this pinned pointer.
411     ///
412     /// This is a generic method to go from `&mut Pin<SmartPointer<T>>` to `Pin<&mut T>`.
413     /// It is safe because, as part of the contract of `Pin::new_unchecked`,
414     /// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
415     /// "Malicious" implementations of `SmartPointer::DerefMut` are likewise
416     /// ruled out by the contract of `Pin::new_unchecked`.
417     #[stable(feature = "pin", since = "1.33.0")]
418     #[inline(always)]
419     pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
420         unsafe { Pin::new_unchecked(&mut *self.pointer) }
421     }
422
423     /// Assigns a new value to the memory behind the pinned reference.
424     ///
425     /// This overwrites pinned data, but that is okay: its destructor gets
426     /// run before being overwritten, so no pinning guarantee is violated.
427     #[stable(feature = "pin", since = "1.33.0")]
428     #[inline(always)]
429     pub fn set(self: &mut Pin<P>, value: P::Target)
430     where
431         P::Target: Sized,
432     {
433         *(self.pointer) = value;
434     }
435 }
436
437 impl<'a, T: ?Sized> Pin<&'a T> {
438     /// Constructs a new pin by mapping the interior value.
439     ///
440     /// For example, if you  wanted to get a `Pin` of a field of something,
441     /// you could use this to get access to that field in one line of code.
442     /// However, there are several gotchas with these "pinning projections";
443     /// see the [`pin` module] documentation for further details on that topic.
444     ///
445     /// # Safety
446     ///
447     /// This function is unsafe. You must guarantee that the data you return
448     /// will not move so long as the argument value does not move (for example,
449     /// because it is one of the fields of that value), and also that you do
450     /// not move out of the argument you receive to the interior function.
451     ///
452     /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
453     #[stable(feature = "pin", since = "1.33.0")]
454     pub unsafe fn map_unchecked<U, F>(self: Pin<&'a T>, func: F) -> Pin<&'a U> where
455         F: FnOnce(&T) -> &U,
456     {
457         let pointer = &*self.pointer;
458         let new_pointer = func(pointer);
459         Pin::new_unchecked(new_pointer)
460     }
461
462     /// Gets a shared reference out of a pin.
463     ///
464     /// This is safe because it is not possible to move out of a shared reference.
465     /// It may seem like there is an issue here with interior mutability: in fact,
466     /// it *is* possible to move a `T` out of a `&RefCell<T>`. However, this is
467     /// not a problem as long as there does not also exist a `Pin<&T>` pointing
468     /// to the same data, and `RefCell` does not let you create a pinned reference
469     /// to its contents. See the discussion on ["pinning projections"] for further
470     /// details.
471     ///
472     /// Note: `Pin` also implements `Deref` to the target, which can be used
473     /// to access the inner value. However, `Deref` only provides a reference
474     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
475     /// the `Pin` itself. This method allows turning the `Pin` into a reference
476     /// with the same lifetime as the original `Pin`.
477     ///
478     /// ["pinning projections"]: ../../std/pin/index.html#projections-and-structural-pinning
479     #[stable(feature = "pin", since = "1.33.0")]
480     #[inline(always)]
481     pub fn get_ref(self: Pin<&'a T>) -> &'a T {
482         self.pointer
483     }
484 }
485
486 impl<'a, T: ?Sized> Pin<&'a mut T> {
487     /// Converts this `Pin<&mut T>` into a `Pin<&T>` with the same lifetime.
488     #[stable(feature = "pin", since = "1.33.0")]
489     #[inline(always)]
490     pub fn into_ref(self: Pin<&'a mut T>) -> Pin<&'a T> {
491         Pin { pointer: self.pointer }
492     }
493
494     /// Gets a mutable reference to the data inside of this `Pin`.
495     ///
496     /// This requires that the data inside this `Pin` is `Unpin`.
497     ///
498     /// Note: `Pin` also implements `DerefMut` to the data, which can be used
499     /// to access the inner value. However, `DerefMut` only provides a reference
500     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
501     /// the `Pin` itself. This method allows turning the `Pin` into a reference
502     /// with the same lifetime as the original `Pin`.
503     #[stable(feature = "pin", since = "1.33.0")]
504     #[inline(always)]
505     pub fn get_mut(self: Pin<&'a mut T>) -> &'a mut T
506         where T: Unpin,
507     {
508         self.pointer
509     }
510
511     /// Gets a mutable reference to the data inside of this `Pin`.
512     ///
513     /// # Safety
514     ///
515     /// This function is unsafe. You must guarantee that you will never move
516     /// the data out of the mutable reference you receive when you call this
517     /// function, so that the invariants on the `Pin` type can be upheld.
518     ///
519     /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
520     /// instead.
521     #[stable(feature = "pin", since = "1.33.0")]
522     #[inline(always)]
523     pub unsafe fn get_unchecked_mut(self: Pin<&'a mut T>) -> &'a mut T {
524         self.pointer
525     }
526
527     /// Construct a new pin by mapping the interior value.
528     ///
529     /// For example, if you  wanted to get a `Pin` of a field of something,
530     /// you could use this to get access to that field in one line of code.
531     /// However, there are several gotchas with these "pinning projections";
532     /// see the [`pin` module] documentation for further details on that topic.
533     ///
534     /// # Safety
535     ///
536     /// This function is unsafe. You must guarantee that the data you return
537     /// will not move so long as the argument value does not move (for example,
538     /// because it is one of the fields of that value), and also that you do
539     /// not move out of the argument you receive to the interior function.
540     ///
541     /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
542     #[stable(feature = "pin", since = "1.33.0")]
543     pub unsafe fn map_unchecked_mut<U, F>(self: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
544         F: FnOnce(&mut T) -> &mut U,
545     {
546         let pointer = Pin::get_unchecked_mut(self);
547         let new_pointer = func(pointer);
548         Pin::new_unchecked(new_pointer)
549     }
550 }
551
552 #[stable(feature = "pin", since = "1.33.0")]
553 impl<P: Deref> Deref for Pin<P> {
554     type Target = P::Target;
555     fn deref(&self) -> &P::Target {
556         Pin::get_ref(Pin::as_ref(self))
557     }
558 }
559
560 #[stable(feature = "pin", since = "1.33.0")]
561 impl<P: DerefMut> DerefMut for Pin<P>
562 where
563     P::Target: Unpin
564 {
565     fn deref_mut(&mut self) -> &mut P::Target {
566         Pin::get_mut(Pin::as_mut(self))
567     }
568 }
569
570 #[unstable(feature = "receiver_trait", issue = "0")]
571 impl<P: Receiver> Receiver for Pin<P> {}
572
573 #[stable(feature = "pin", since = "1.33.0")]
574 impl<P: fmt::Debug> fmt::Debug for Pin<P> {
575     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
576         fmt::Debug::fmt(&self.pointer, f)
577     }
578 }
579
580 #[stable(feature = "pin", since = "1.33.0")]
581 impl<P: fmt::Display> fmt::Display for Pin<P> {
582     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
583         fmt::Display::fmt(&self.pointer, f)
584     }
585 }
586
587 #[stable(feature = "pin", since = "1.33.0")]
588 impl<P: fmt::Pointer> fmt::Pointer for Pin<P> {
589     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
590         fmt::Pointer::fmt(&self.pointer, f)
591     }
592 }
593
594 // Note: this means that any impl of `CoerceUnsized` that allows coercing from
595 // a type that impls `Deref<Target=impl !Unpin>` to a type that impls
596 // `Deref<Target=Unpin>` is unsound. Any such impl would probably be unsound
597 // for other reasons, though, so we just need to take care not to allow such
598 // impls to land in std.
599 #[stable(feature = "pin", since = "1.33.0")]
600 impl<P, U> CoerceUnsized<Pin<U>> for Pin<P>
601 where
602     P: CoerceUnsized<U>,
603 {}
604
605 #[stable(feature = "pin", since = "1.33.0")]
606 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
607 where
608     P: DispatchFromDyn<U>,
609 {}