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