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