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