Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit c6fd027

Browse files
committedFeb 22, 2019
Auto merge of #58574 - RalfJung:pin, r=Mark-Simulacrum
improve Pin documentation Incorporates a bunch of the documentation-related comments that came up when discussing `Pin` stabilization. Cc @alexcrichton @withoutboats @cramertj @jonhoo Fixes #58130
2 parents d1f8970 + 497439c commit c6fd027

File tree

2 files changed

+310
-49
lines changed

2 files changed

+310
-49
lines changed
 

‎src/libcore/marker.rs

Lines changed: 18 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -597,34 +597,43 @@ unsafe impl<T: ?Sized> Freeze for &mut T {}
597597

598598
/// Types which can be safely moved after being pinned.
599599
///
600-
/// Since Rust itself has no notion of immovable types, and will consider moves to always be safe,
600+
/// Since Rust itself has no notion of immovable types, and considers moves
601+
/// (e.g. through assignment or [`mem::replace`]) to always be safe,
601602
/// this trait cannot prevent types from moving by itself.
602603
///
603-
/// Instead it can be used to prevent moves through the type system,
604-
/// by controlling the behavior of pointers wrapped in the [`Pin`] wrapper,
604+
/// Instead it is used to prevent moves through the type system,
605+
/// by controlling the behavior of pointers `P` wrapped in the [`Pin<P>`] wrapper,
605606
/// which "pin" the type in place by not allowing it to be moved out of them.
606607
/// See the [`pin module`] documentation for more information on pinning.
607608
///
608609
/// Implementing this trait lifts the restrictions of pinning off a type,
609-
/// which then allows it to move out with functions such as [`replace`].
610+
/// which then allows it to move out with functions such as [`mem::replace`].
611+
///
612+
/// `Unpin` has no consequence at all for non-pinned data. In particular,
613+
/// [`mem::replace`] happily moves `!Unpin` data (it works for any `&mut T`, not
614+
/// just when `T: Unpin`). However, you cannot use
615+
/// [`mem::replace`] on data wrapped inside a [`Pin<P>`] because you cannot get the
616+
/// `&mut T` you need for that, and *that* is what makes this system work.
610617
///
611618
/// So this, for example, can only be done on types implementing `Unpin`:
612619
///
613620
/// ```rust
614-
/// use std::mem::replace;
621+
/// use std::mem;
615622
/// use std::pin::Pin;
616623
///
617624
/// let mut string = "this".to_string();
618625
/// let mut pinned_string = Pin::new(&mut string);
619626
///
620-
/// // dereferencing the pointer mutably is only possible because String implements Unpin
621-
/// replace(&mut *pinned_string, "other".to_string());
627+
/// // We need a mutable reference to call `mem::replace`.
628+
/// // We can obtain such a reference by (implicitly) invoking `Pin::deref_mut`,
629+
/// // but that is only possible because `String` implements `Unpin`.
630+
/// mem::replace(&mut *pinned_string, "other".to_string());
622631
/// ```
623632
///
624633
/// This trait is automatically implemented for almost every type.
625634
///
626-
/// [`replace`]: ../../std/mem/fn.replace.html
627-
/// [`Pin`]: ../pin/struct.Pin.html
635+
/// [`mem::replace`]: ../../std/mem/fn.replace.html
636+
/// [`Pin<P>`]: ../pin/struct.Pin.html
628637
/// [`pin module`]: ../../std/pin/index.html
629638
#[stable(feature = "pin", since = "1.33.0")]
630639
#[cfg_attr(not(stage0), lang = "unpin")]

‎src/libcore/pin.rs

Lines changed: 292 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -2,45 +2,63 @@
22
//!
33
//! It is sometimes useful to have objects that are guaranteed to not move,
44
//! in the sense that their placement in memory does not change, and can thus be relied upon.
5-
//!
65
//! A prime example of such a scenario would be building self-referential structs,
76
//! since moving an object with pointers to itself will invalidate them,
87
//! which could cause undefined behavior.
98
//!
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+
//!
1013
//! By default, all types in Rust are movable. Rust allows passing all types by-value,
11-
//! and common smart-pointer types such as `Box`, `Rc`, and `&mut` allow replacing and
12-
//! moving the values they contain. In order to prevent objects from moving, they must
13-
//! be pinned by wrapping a pointer to the data in the [`Pin`] type.
14-
//! Doing this prohibits moving the value behind the pointer.
15-
//! For example, `Pin<Box<T>>` functions much like a regular `Box<T>`,
16-
//! but doesn't allow moving `T`. The pointer value itself (the `Box`) can still be moved,
17-
//! but the value behind it cannot.
18-
//!
19-
//! Since data can be moved out of `&mut` and `Box` with functions such as [`swap`],
20-
//! changing the location of the underlying data, [`Pin`] prohibits accessing the
21-
//! underlying pointer type (the `&mut` or `Box`) directly, and provides its own set of
22-
//! APIs for accessing and using the value. [`Pin`] also guarantees that no other
23-
//! functions will move the pointed-to value. This allows for the creation of
24-
//! self-references and other special behaviors that are only possible for unmovable
25-
//! values.
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+
//! ```
2630
//!
27-
//! However, these restrictions are usually not necessary. Many types are always freely
28-
//! movable. These types implement the [`Unpin`] auto-trait, which nullifies the effect
29-
//! of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function identically, as do
30-
//! `Pin<&mut T>` and `&mut T`.
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`]).
3136
//!
32-
//! Note that pinning and `Unpin` only affect the pointed-to type. For example, whether
33-
//! or not `Box<T>` is `Unpin` has no affect on the behavior of `Pin<Box<T>>`. Similarly,
34-
//! `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves, even though the
35-
//! `T` underneath them isn't, because the pointers in `Pin<Box<_>>` and `Pin<&mut _>`
36-
//! are always freely movable, even if the data they point to isn't.
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.
3745
//!
38-
//! [`Pin`]: struct.Pin.html
39-
//! [`Unpin`]: ../../std/marker/trait.Unpin.html
40-
//! [`swap`]: ../../std/mem/fn.swap.html
41-
//! [`Box`]: ../../std/boxed/struct.Box.html
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).
4260
//!
43-
//! # Examples
61+
//! # Example: self-referential struct
4462
//!
4563
//! ```rust
4664
//! use std::pin::Pin;
@@ -94,6 +112,150 @@
94112
//! // let new_unmoved = Unmovable::new("world".to_string());
95113
//! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
96114
//! ```
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 relies on pinning
162+
//! requires unsafe code, but be aware that deciding to make use of pinning
163+
//! in your type (for example by implementing some operation on `Pin<&[mut] Self>`)
164+
//! has consequences for your `Drop` implementation as well: if an element
165+
//! of your type could have been pinned, you must treat Drop as implicitly taking
166+
//! `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 and
175+
//! the fields of a struct. When can a struct have a "pinning projection", i.e.,
176+
//! an operation with type `fn(Pin<&[mut] Struct>) -> Pin<&[mut] Field>`?
177+
//! In a similar vein, when can a generic wrapper type (such as `Vec<T>`, `Box<T>`, or `RefCell<T>`)
178+
//! have an operation with type `fn(Pin<&[mut] Wrapper<T>>) -> Pin<&[mut] T>`?
179+
//!
180+
//! Having a pinning projection for some field means that pinning is "structural":
181+
//! when the wrapper is pinned, the field must be considered pinned, too.
182+
//! After all, the pinning projection lets us get a `Pin<&[mut] Field>`.
183+
//!
184+
//! However, structural pinning comes with a few extra requirements, so not all
185+
//! wrappers can be structural and hence not all wrappers can offer pinning projections:
186+
//!
187+
//! 1. The wrapper must only be [`Unpin`] if all the structural fields are
188+
//! `Unpin`. This is the default, but `Unpin` is a safe trait, so as the author of
189+
//! the wrapper it is your responsibility *not* to add something like
190+
//! `impl<T> Unpin for Wrapper<T>`. (Notice that adding a projection operation
191+
//! requires unsafe code, so the fact that `Unpin` is a safe trait does not break
192+
//! the principle that you only have to worry about any of this if you use `unsafe`.)
193+
//! 2. The destructor of the wrapper must not move structural fields out of its argument. This
194+
//! is the exact point that was raised in the [previous section][drop-impl]: `drop` takes
195+
//! `&mut self`, but the wrapper (and hence its fields) might have been pinned before.
196+
//! You have to guarantee that you do not move a field inside your `Drop` implementation.
197+
//! In particular, as explained previously, this means that your wrapper type must *not*
198+
//! be `#[repr(packed)]`.
199+
//! 3. You must make sure that you uphold the [`Drop` guarantee][drop-guarantee]:
200+
//! once your wrapper is pinned, the memory that contains the
201+
//! content is not overwritten or deallocated without calling the content's destructors.
202+
//! This can be tricky, as witnessed by `VecDeque<T>`: the destructor of `VecDeque<T>` can fail
203+
//! to call `drop` on all elements if one of the destructors panics. This violates the
204+
//! `Drop` guarantee, because it can lead to elements being deallocated without
205+
//! their destructor being called. (`VecDeque` has no pinning projections, so this
206+
//! does not cause unsoundness.)
207+
//! 4. You must not offer any other operations that could lead to data being moved out of
208+
//! the fields when your type is pinned. For example, if the wrapper contains an
209+
//! `Option<T>` and there is a `take`-like operation with type
210+
//! `fn(Pin<&mut Wrapper<T>>) -> Option<T>`,
211+
//! that operation can be used to move a `T` out of a pinned `Wrapper<T>` -- which means
212+
//! pinning cannot be structural.
213+
//!
214+
//! For a more complex example of moving data out of a pinned type, imagine if `RefCell<T>`
215+
//! had a method `fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>`.
216+
//! Then we could do the following:
217+
//! ```compile_fail
218+
//! fn exploit_ref_cell<T>(rc: Pin<&mut RefCell<T>) {
219+
//! { let p = rc.as_mut().get_pin_mut(); } // Here we get pinned access to the `T`.
220+
//! let rc_shr: &RefCell<T> = rc.into_ref().get_ref();
221+
//! let b = rc_shr.borrow_mut();
222+
//! let content = &mut *b; // And here we have `&mut T` to the same data.
223+
//! }
224+
//! ```
225+
//! This is catastrophic, it means we can first pin the content of the `RefCell<T>`
226+
//! (using `RefCell::get_pin_mut`) and then move that content using the mutable
227+
//! reference we got later.
228+
//!
229+
//! For a type like `Vec<T>`, both possibilites (structural pinning or not) make sense,
230+
//! and the choice is up to the author. A `Vec<T>` with structural pinning could
231+
//! have `get_pin`/`get_pin_mut` projections. However, it could *not* allow calling
232+
//! `pop` on a pinned `Vec<T>` because that would move the (structurally pinned) contents!
233+
//! Nor could it allow `push`, which might reallocate and thus also move the contents.
234+
//! A `Vec<T>` without structural pinning could `impl<T> Unpin for Vec<T>`, because the contents
235+
//! are never pinned and the `Vec<T>` itself is fine with being moved as well.
236+
//!
237+
//! In the standard library, pointer types generally do not have structural pinning,
238+
//! and thus they do not offer pinning projections. This is why `Box<T>: Unpin` holds for all `T`.
239+
//! It makes sense to do this for pointer types, because moving the `Box<T>`
240+
//! does not actually move the `T`: the `Box<T>` can be freely movable (aka `Unpin`) even if the `T`
241+
//! is not. In fact, even `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves,
242+
//! for the same reason: their contents (the `T`) are pinned, but the pointers themselves
243+
//! can be moved without moving the pinned data. For both `Box<T>` and `Pin<Box<T>>`,
244+
//! whether the content is pinned is entirely independent of whether the pointer is
245+
//! pinned, meaning pinning is *not* structural.
246+
//!
247+
//! [`Pin<P>`]: struct.Pin.html
248+
//! [`Unpin`]: ../../std/marker/trait.Unpin.html
249+
//! [`Deref`]: ../../std/ops/trait.Deref.html
250+
//! [`DerefMut`]: ../../std/ops/trait.DerefMut.html
251+
//! [`mem::swap`]: ../../std/mem/fn.swap.html
252+
//! [`mem::forget`]: ../../std/mem/fn.forget.html
253+
//! [`Box<T>`]: ../../std/boxed/struct.Box.html
254+
//! [`Vec::set_len`]: ../../std/vec/struct.Vec.html#method.set_len
255+
//! [`None`]: ../../std/option/enum.Option.html#variant.None
256+
//! [`Some(v)`]: ../../std/option/enum.Option.html#variant.Some
257+
//! [drop-impl]: #drop-implementation
258+
//! [drop-guarantee]: #drop-guarantee
97259
98260
#![stable(feature = "pin", since = "1.33.0")]
99261

@@ -169,8 +331,13 @@ impl<P: Deref> Pin<P>
169331
where
170332
P::Target: Unpin,
171333
{
172-
/// Construct a new `Pin` around a pointer to some data of a type that
173-
/// implements `Unpin`.
334+
/// Construct a new `Pin<P>` around a pointer to some data of a type that
335+
/// implements [`Unpin`].
336+
///
337+
/// Unlike `Pin::new_unchecked`, this method is safe because the pointer
338+
/// `P` dereferences to an [`Unpin`] type, which cancels the pinning guarantees.
339+
///
340+
/// [`Unpin`]: ../../std/marker/trait.Unpin.html
174341
#[stable(feature = "pin", since = "1.33.0")]
175342
#[inline(always)]
176343
pub fn new(pointer: P) -> Pin<P> {
@@ -181,25 +348,83 @@ where
181348
}
182349

183350
impl<P: Deref> Pin<P> {
184-
/// Construct a new `Pin` around a reference to some data of a type that
351+
/// Construct a new `Pin<P>` around a reference to some data of a type that
185352
/// may or may not implement `Unpin`.
186353
///
354+
/// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
355+
/// instead.
356+
///
187357
/// # Safety
188358
///
189359
/// This constructor is unsafe because we cannot guarantee that the data
190-
/// pointed to by `pointer` is pinned. If the constructed `Pin<P>` does
191-
/// not guarantee that the data `P` points to is pinned, constructing a
192-
/// `Pin<P>` is undefined behavior.
360+
/// pointed to by `pointer` is pinned, meaning that the data will not be moved or
361+
/// its storage invalidated until it gets dropped. If the constructed `Pin<P>` does
362+
/// not guarantee that the data `P` points to is pinned, that is a violation of
363+
/// the API contract and may lead to undefined behavior in later (safe) operations.
193364
///
194-
/// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
195-
/// instead.
365+
/// By using this method, you are making a promise about the `P::Deref` and
366+
/// `P::DerefMut` implementations, if they exist. Most importantly, they
367+
/// must not move out of their `self` arguments: `Pin::as_mut` and `Pin::as_ref`
368+
/// will call `DerefMut::deref_mut` and `Deref::deref` *on the pinned pointer*
369+
/// and expect these methods to uphold the pinning invariants.
370+
/// Moreover, by calling this method you promise that the reference `P`
371+
/// dereferences to will not be moved out of again; in particular, it
372+
/// must not be possible to obtain a `&mut P::Target` and then
373+
/// move out of that reference (using, for example [`mem::swap`]).
374+
///
375+
/// For example, calling `Pin::new_unchecked` on an `&'a mut T` is unsafe because
376+
/// while you are able to pin it for the given lifetime `'a`, you have no control
377+
/// over whether it is kept pinned once `'a` ends:
378+
/// ```
379+
/// use std::mem;
380+
/// use std::pin::Pin;
381+
///
382+
/// fn move_pinned_ref<T>(mut a: T, mut b: T) {
383+
/// unsafe {
384+
/// let p: Pin<&mut T> = Pin::new_unchecked(&mut a);
385+
/// // This should mean the pointee `a` can never move again.
386+
/// }
387+
/// mem::swap(&mut a, &mut b);
388+
/// // The address of `a` changed to `b`'s stack slot, so `a` got moved even
389+
/// // though we have previously pinned it! We have violated the pinning API contract.
390+
/// }
391+
/// ```
392+
/// A value, once pinned, must remain pinned forever (unless its type implements `Unpin`).
393+
///
394+
/// Similarily, calling `Pin::new_unchecked` on an `Rc<T>` is unsafe because there could be
395+
/// aliases to the same data that are not subject to the pinning restrictions:
396+
/// ```
397+
/// use std::rc::Rc;
398+
/// use std::pin::Pin;
399+
///
400+
/// fn move_pinned_rc<T>(mut x: Rc<T>) {
401+
/// let pinned = unsafe { Pin::new_unchecked(x.clone()) };
402+
/// {
403+
/// let p: Pin<&T> = pinned.as_ref();
404+
/// // This should mean the pointee can never move again.
405+
/// }
406+
/// drop(pinned);
407+
/// let content = Rc::get_mut(&mut x).unwrap();
408+
/// // Now, if `x` was the only reference, we have a mutable reference to
409+
/// // data that we pinned above, which we could use to move it as we have
410+
/// // seen in the previous example. We have violated the pinning API contract.
411+
/// }
412+
/// ```
413+
///
414+
/// [`mem::swap`]: ../../std/mem/fn.swap.html
196415
#[stable(feature = "pin", since = "1.33.0")]
197416
#[inline(always)]
198417
pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
199418
Pin { pointer }
200419
}
201420

202421
/// Gets a pinned shared reference from this pinned pointer.
422+
///
423+
/// This is a generic method to go from `&Pin<Pointer<T>>` to `Pin<&T>`.
424+
/// It is safe because, as part of the contract of `Pin::new_unchecked`,
425+
/// the pointee cannot move after `Pin<Pointer<T>>` got created.
426+
/// "Malicious" implementations of `Pointer::Deref` are likewise
427+
/// ruled out by the contract of `Pin::new_unchecked`.
203428
#[stable(feature = "pin", since = "1.33.0")]
204429
#[inline(always)]
205430
pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
@@ -209,13 +434,22 @@ impl<P: Deref> Pin<P> {
209434

210435
impl<P: DerefMut> Pin<P> {
211436
/// Gets a pinned mutable reference from this pinned pointer.
437+
///
438+
/// This is a generic method to go from `&mut Pin<Pointer<T>>` to `Pin<&mut T>`.
439+
/// It is safe because, as part of the contract of `Pin::new_unchecked`,
440+
/// the pointee cannot move after `Pin<Pointer<T>>` got created.
441+
/// "Malicious" implementations of `Pointer::DerefMut` are likewise
442+
/// ruled out by the contract of `Pin::new_unchecked`.
212443
#[stable(feature = "pin", since = "1.33.0")]
213444
#[inline(always)]
214445
pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
215446
unsafe { Pin::new_unchecked(&mut *self.pointer) }
216447
}
217448

218-
/// Assign a new value to the memory behind the pinned reference.
449+
/// Assigns a new value to the memory behind the pinned reference.
450+
///
451+
/// This overwrites pinned data, but that is okay: its destructor gets
452+
/// run before being overwritten, so no pinning guarantee is violated.
219453
#[stable(feature = "pin", since = "1.33.0")]
220454
#[inline(always)]
221455
pub fn set(self: &mut Pin<P>, value: P::Target)
@@ -227,17 +461,21 @@ impl<P: DerefMut> Pin<P> {
227461
}
228462

229463
impl<'a, T: ?Sized> Pin<&'a T> {
230-
/// Construct a new pin by mapping the interior value.
464+
/// Constructs a new pin by mapping the interior value.
231465
///
232466
/// For example, if you wanted to get a `Pin` of a field of something,
233467
/// you could use this to get access to that field in one line of code.
468+
/// However, there are several gotchas with these "pinning projections";
469+
/// see the [`pin` module] documentation for further details on that topic.
234470
///
235471
/// # Safety
236472
///
237473
/// This function is unsafe. You must guarantee that the data you return
238474
/// will not move so long as the argument value does not move (for example,
239475
/// because it is one of the fields of that value), and also that you do
240476
/// not move out of the argument you receive to the interior function.
477+
///
478+
/// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
241479
#[stable(feature = "pin", since = "1.33.0")]
242480
pub unsafe fn map_unchecked<U, F>(self: Pin<&'a T>, func: F) -> Pin<&'a U> where
243481
F: FnOnce(&T) -> &U,
@@ -249,11 +487,21 @@ impl<'a, T: ?Sized> Pin<&'a T> {
249487

250488
/// Gets a shared reference out of a pin.
251489
///
490+
/// This is safe because it is not possible to move out of a shared reference.
491+
/// It may seem like there is an issue here with interior mutability: in fact,
492+
/// it *is* possible to move a `T` out of a `&RefCell<T>`. However, this is
493+
/// not a problem as long as there does not also exist a `Pin<&T>` pointing
494+
/// to the same data, and `RefCell<T>` does not let you create a pinned reference
495+
/// to its contents. See the discussion on ["pinning projections"] for further
496+
/// details.
497+
///
252498
/// Note: `Pin` also implements `Deref` to the target, which can be used
253499
/// to access the inner value. However, `Deref` only provides a reference
254500
/// that lives for as long as the borrow of the `Pin`, not the lifetime of
255501
/// the `Pin` itself. This method allows turning the `Pin` into a reference
256502
/// with the same lifetime as the original `Pin`.
503+
///
504+
/// ["pinning projections"]: ../../std/pin/index.html#projections-and-structural-pinning
257505
#[stable(feature = "pin", since = "1.33.0")]
258506
#[inline(always)]
259507
pub fn get_ref(self: Pin<&'a T>) -> &'a T {
@@ -306,13 +554,17 @@ impl<'a, T: ?Sized> Pin<&'a mut T> {
306554
///
307555
/// For example, if you wanted to get a `Pin` of a field of something,
308556
/// you could use this to get access to that field in one line of code.
557+
/// However, there are several gotchas with these "pinning projections";
558+
/// see the [`pin` module] documentation for further details on that topic.
309559
///
310560
/// # Safety
311561
///
312562
/// This function is unsafe. You must guarantee that the data you return
313563
/// will not move so long as the argument value does not move (for example,
314564
/// because it is one of the fields of that value), and also that you do
315565
/// not move out of the argument you receive to the interior function.
566+
///
567+
/// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
316568
#[stable(feature = "pin", since = "1.33.0")]
317569
pub unsafe fn map_unchecked_mut<U, F>(self: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
318570
F: FnOnce(&mut T) -> &mut U,

0 commit comments

Comments
 (0)
Please sign in to comment.