Skip to content

Commit 4059889

Browse files
committed
improve Pin documentation
1 parent 32471f7 commit 4059889

File tree

2 files changed

+190
-20
lines changed

2 files changed

+190
-20
lines changed

src/libcore/marker.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -597,7 +597,8 @@ 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 will consider moves
601+
/// (e.g. through assignment or [`mem::replace`]) to always be safe,
601602
/// this trait cannot prevent types from moving by itself.
602603
///
603604
/// Instead it can be used to prevent moves through the type system,
@@ -606,7 +607,12 @@ unsafe impl<T: ?Sized> Freeze for &mut T {}
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`] will happily move `!Unpin` data. However, you cannot use
614+
/// [`mem::replace`] on data wrapped inside a [`Pin`], and *that* is what makes
615+
/// this system work.
610616
///
611617
/// So this, for example, can only be done on types implementing `Unpin`:
612618
///
@@ -623,7 +629,7 @@ unsafe impl<T: ?Sized> Freeze for &mut T {}
623629
///
624630
/// This trait is automatically implemented for almost every type.
625631
///
626-
/// [`replace`]: ../../std/mem/fn.replace.html
632+
/// [`mem::replace`]: ../../std/mem/fn.replace.html
627633
/// [`Pin`]: ../pin/struct.Pin.html
628634
/// [`pin module`]: ../../std/pin/index.html
629635
#[stable(feature = "pin", since = "1.33.0")]

src/libcore/pin.rs

Lines changed: 181 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,30 @@
1616
//! but doesn't allow moving `T`. The pointer value itself (the `Box`) can still be moved,
1717
//! but the value behind it cannot.
1818
//!
19-
//! Since data can be moved out of `&mut` and `Box` with functions such as [`swap`],
19+
//! Since data can be moved out of `&mut` and `Box` with functions such as [`mem::swap`],
2020
//! changing the location of the underlying data, [`Pin`] prohibits accessing the
2121
//! underlying pointer type (the `&mut` or `Box`) directly, and provides its own set of
2222
//! APIs for accessing and using the value. [`Pin`] also guarantees that no other
2323
//! functions will move the pointed-to value. This allows for the creation of
2424
//! self-references and other special behaviors that are only possible for unmovable
2525
//! values.
2626
//!
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`.
27+
//! It is worth reiterating that [`Pin`] does *not* change the fact that the Rust compiler
28+
//! considers all types movable. [`mem::swap`] remains callable for any `T`. Instead, `Pin`
29+
//! prevents certain *values* (pointed to by pointers wrapped in `Pin`) from being
30+
//! moved by making it impossible to call methods like [`mem::swap`] on them.
3131
//!
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.
32+
//! # `Unpin`
3733
//!
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
34+
//! However, these restrictions are usually not necessary. Many types are always freely
35+
//! movable, even when pinned. These types implement the [`Unpin`] auto-trait, which
36+
//! nullifies the effect of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function
37+
//! identically, as do `Pin<&mut T>` and `&mut T`.
38+
//!
39+
//! Note that pinning and `Unpin` only affect the pointed-to type, not the pointer
40+
//! type itself that got wrapped in `Pin`. For example, whether or not `Box<T>` is
41+
//! `Unpin` has no affect on the behavior of `Pin<Box<T>>` (here, `T` is the
42+
//! pointed-to type).
4243
//!
4344
//! # Examples
4445
//!
@@ -94,6 +95,106 @@
9495
//! // let new_unmoved = Unmovable::new("world".to_string());
9596
//! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
9697
//! ```
98+
//!
99+
//! # `Drop` guarantee
100+
//!
101+
//! The purpose of pinning is to be able to rely on the placement of some data in memory.
102+
//! To make this work, not just moving the data is restricted; deallocating or overwriting
103+
//! it is restricted, too. Concretely, for pinned data you have to maintain the invariant
104+
//! that *it will not get overwritten or deallocated until `drop` was called*.
105+
//! ("Overwriting" here refers to other ways of invalidating storage, such as switching
106+
//! from one enum variant to another.)
107+
//!
108+
//! The purpose of this guarantee is to allow data structures that store pointers
109+
//! to pinned data. For example, in an intrusive doubly-linked list, every element
110+
//! will have pointers to its predecessor and successor in the list. Every element
111+
//! will be pinned, because moving the elements around would invalidate the pointers.
112+
//! Moreover, the `Drop` implemenetation of a linked list element will patch the pointers
113+
//! of its predecessor and successor to remove itself from the list. Clearly, if an element
114+
//! could be deallocated or overwritten without calling `drop`, the pointers into it
115+
//! from its neighbouring elements would become invalid, breaking the data structure.
116+
//!
117+
//! Notice that this guarantee does *not* mean that memory does not leak! It is still
118+
//! completely okay not to ever call `drop` on a pinned element (e.g., you can still
119+
//! call [`mem::forget`] on a `Pin<Box<T>>`). What you may not do is free or reuse the storage
120+
//! without calling `drop`.
121+
//!
122+
//! # `Drop` implementation
123+
//!
124+
//! If your type relies on pinning (for example, because it contains internal
125+
//! references, or because you are implementing something like the intrusive
126+
//! doubly-linked list mentioned in the previous section), you have to be careful
127+
//! when implementing `Drop`: notice that `drop` takes `&mut self`, but this
128+
//! will be called even if your type was previously pinned! It is as if the
129+
//! compiler automatically called `get_unchecked_mut`. This can never cause
130+
//! a problem in safe code because implementing a type that relies on pinning
131+
//! requires unsafe code, but be aware that deciding to make use of pinning
132+
//! in your type (for example by implementing some operation on `Pin<&[mut] Self>`)
133+
//! has consequences for your `Drop` implemenetation as well.
134+
//!
135+
//! # Projections and Structural Pinning
136+
//!
137+
//! One interesting question arises when considering pinning and "container types" --
138+
//! types such as `Vec` or `Box` but also `RefCell`; types that serve as wrappers
139+
//! around other types. When can such a type have a "projection" operation, an
140+
//! operation with type `fn(Pin<&[mut] Container<T>>) -> Pin<&[mut] T>`?
141+
//! This does not just apply to generic container types, even for normal structs
142+
//! the question arises whether `fn(Pin<&[mut] Struct>) -> Pin<&[mut] Field>`
143+
//! is an operation that can be soundly added to the API.
144+
//!
145+
//! This question is closely related to the question of whether pinning is "structural":
146+
//! when you have pinned a container, have you pinned its contents? Adding a
147+
//! projection to the API answers that question with a "yes" by offering pinned access
148+
//! to the contents.
149+
//!
150+
//! In general, as the author of a type you get to decide whether pinning is structural, and
151+
//! whether projections are provided. However, there are a couple requirements to be
152+
//! upheld when adding projection operations:
153+
//!
154+
//! 1. The container must only be [`Unpin`] if all its fields are `Unpin`. This is the default,
155+
//! but `Unpin` is a safe trait, so as the author of the container it is your responsibility
156+
//! *not* to add something like `impl<T> Unpin for Container<T>`. (Notice that adding a
157+
//! projection operation requires unsafe code, so the fact that `Unpin` is a safe trait
158+
//! does not break the principle that you only have to worry about any of this if
159+
//! you use `unsafe`.)
160+
//! 2. The destructor of the container must not move out of its argument. This is the exact
161+
//! point that was raised in the [previous section][drop-impl]: `drop` takes `&mut self`,
162+
//! but the container (and hence its fields) might have been pinned before.
163+
//! You have to guarantee that you do not move a field inside your `Drop` implementation.
164+
//! 3. Your container type must *not* be `#[repr(packed)]`. Packed structs have their fields
165+
//! moved around when they are dropped to properly align them, which is in conflict with
166+
//! claiming that the fields are pinned when your struct is.
167+
//! 4. You must make sure that you uphold the [`Drop` guarantee][drop-guarantee]:
168+
//! you must make sure that, once your container is pinned, the memory containing the
169+
//! content is not overwritten or deallocated without calling the content's destructors.
170+
//! This can be tricky, as witnessed by `VecDeque`: the destructor of `VecDeque` can fail
171+
//! to call `drop` on all elements if one of the destructors panics. This violates the
172+
//! `Drop` guarantee, because it can lead to elements being deallocated without
173+
//! their destructor being called.
174+
//! 5. You must not offer any other operations that could lead to data being moved out of
175+
//! the fields when your type is pinned. This is usually not a concern, but can become
176+
//! tricky when interior mutability is involved. For example, imagine `RefCell`
177+
//! would have a method `fn get_pin_mut(self: Pin<&mut Self>) -> Pin<&mut T>`.
178+
//! This would be catastrophic, because it is possible to move out of a pinned
179+
//! `RefCell`: from `x: Pin<&mut RefCell<T>>`, use `let y = x.into_ref().get_ref()` to obtain
180+
//! `y: &RefCell<T>`, and from there use `y.borrow_mut().deref_mut()` to obtain `&mut T`
181+
//! which can be used with [`mem::swap`].
182+
//!
183+
//! On the other hand, if you decide *not* to offer any pinning projections, you
184+
//! are free to do `impl<T> Unpin for Container<T>`. In the standard library,
185+
//! we do this for all pointer types: `Box<T>: Unpin` holds for all `T`.
186+
//! It makes a lot of sense to do this for pointer types, because moving the `Box<T>`
187+
//! does not actually move the `T`: the `Box<T>` can be freely movable even if the `T`
188+
//! is not. In fact, even `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves,
189+
//! for the same reason.
190+
//!
191+
//! [`Pin`]: struct.Pin.html
192+
//! [`Unpin`]: ../../std/marker/trait.Unpin.html
193+
//! [`mem::swap`]: ../../std/mem/fn.swap.html
194+
//! [`mem::forget`]: ../../std/mem/fn.forget.html
195+
//! [`Box`]: ../../std/boxed/struct.Box.html
196+
//! [drop-impl]: #drop-implementation
197+
//! [drop-guarantee]: #drop-guarantee
97198
98199
#![stable(feature = "pin", since = "1.33.0")]
99200

@@ -170,7 +271,12 @@ where
170271
P::Target: Unpin,
171272
{
172273
/// Construct a new `Pin` around a pointer to some data of a type that
173-
/// implements `Unpin`.
274+
/// implements [`Unpin`].
275+
///
276+
/// Unlike `Pin::new_unchecked`, this method is safe because the pointer
277+
/// `P` dereferences to an [`Unpin`] type, which nullifies the pinning guarantees.
278+
///
279+
/// [`Unpin`]: ../../std/marker/trait.Unpin.html
174280
#[stable(feature = "pin", since = "1.33.0")]
175281
#[inline(always)]
176282
pub fn new(pointer: P) -> Pin<P> {
@@ -191,15 +297,46 @@ impl<P: Deref> Pin<P> {
191297
/// not guarantee that the data `P` points to is pinned, constructing a
192298
/// `Pin<P>` is undefined behavior.
193299
///
300+
/// By using this method, you are making a promise about the `P::Deref` and
301+
/// `P::DerefMut` implementations, if they exist. Most importantly, they
302+
/// must not move out of their `self` arguments: `Pin::as_mut` and `Pin::as_ref`
303+
/// will call `DerefMut::deref_mut` and `Deref::deref` *on the pinned pointer*
304+
/// and expect these methods to uphold the pinning invariants.
305+
/// Moreover, by calling this method you promise that the reference `P`
306+
/// dereferences to will not be moved out of again; in particular, it
307+
/// must not be possible to obtain a `&mut P::Target` and then
308+
/// move out of that reference (using, for example [`replace`]).
309+
///
310+
/// For example, the following is a *violation* of `Pin`'s safety:
311+
/// ```
312+
/// use std::mem;
313+
/// use std::pin::Pin;
314+
///
315+
/// fn foo<T>(mut a: T, b: T) {
316+
/// unsafe { let p = Pin::new_unchecked(&mut a); } // should mean `a` can never move again
317+
/// let a2 = mem::replace(&mut a, b);
318+
/// // the address of `a` changed to `a2`'s stack slot, so `a` got moved even
319+
/// // though we have previously pinned it!
320+
/// }
321+
/// ```
322+
///
194323
/// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
195324
/// instead.
325+
///
326+
/// [`replace`]: ../../std/mem/fn.replace.html
196327
#[stable(feature = "pin", since = "1.33.0")]
197328
#[inline(always)]
198329
pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
199330
Pin { pointer }
200331
}
201332

202333
/// Gets a pinned shared reference from this pinned pointer.
334+
///
335+
/// This is a generic method to go from `&Pin<SmartPointer<T>>` to `Pin<&T>`.
336+
/// It is safe because, as part of the contract of `Pin::new_unchecked`,
337+
/// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
338+
/// "Malicious" implementations of `SmartPointer::Deref` are likewise
339+
/// ruled out by the contract of `Pin::new_unchecked`.
203340
#[stable(feature = "pin", since = "1.33.0")]
204341
#[inline(always)]
205342
pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
@@ -209,13 +346,22 @@ impl<P: Deref> Pin<P> {
209346

210347
impl<P: DerefMut> Pin<P> {
211348
/// Gets a pinned mutable reference from this pinned pointer.
349+
///
350+
/// This is a generic method to go from `&mut Pin<SmartPointer<T>>` to `Pin<&mut T>`.
351+
/// It is safe because, as part of the contract of `Pin::new_unchecked`,
352+
/// the pointee cannot move after `Pin<SmartPointer<T>>` got created.
353+
/// "Malicious" implementations of `SmartPointer::DerefMut` are likewise
354+
/// ruled out by the contract of `Pin::new_unchecked`.
212355
#[stable(feature = "pin", since = "1.33.0")]
213356
#[inline(always)]
214357
pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
215358
unsafe { Pin::new_unchecked(&mut *self.pointer) }
216359
}
217360

218-
/// Assign a new value to the memory behind the pinned reference.
361+
/// Assigns a new value to the memory behind the pinned reference.
362+
///
363+
/// This overwrites pinned data, but that is okay: its destructor gets
364+
/// run before being overwritten, so no pinning guarantee is violated.
219365
#[stable(feature = "pin", since = "1.33.0")]
220366
#[inline(always)]
221367
pub fn set(self: &mut Pin<P>, value: P::Target)
@@ -227,17 +373,21 @@ impl<P: DerefMut> Pin<P> {
227373
}
228374

229375
impl<'a, T: ?Sized> Pin<&'a T> {
230-
/// Construct a new pin by mapping the interior value.
376+
/// Constructs a new pin by mapping the interior value.
231377
///
232378
/// For example, if you wanted to get a `Pin` of a field of something,
233379
/// you could use this to get access to that field in one line of code.
380+
/// However, there are several gotchas with these "pinning projections";
381+
/// see the [`pin` module] documentation for further details on that topic.
234382
///
235383
/// # Safety
236384
///
237385
/// This function is unsafe. You must guarantee that the data you return
238386
/// will not move so long as the argument value does not move (for example,
239387
/// because it is one of the fields of that value), and also that you do
240388
/// not move out of the argument you receive to the interior function.
389+
///
390+
/// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
241391
#[stable(feature = "pin", since = "1.33.0")]
242392
pub unsafe fn map_unchecked<U, F>(self: Pin<&'a T>, func: F) -> Pin<&'a U> where
243393
F: FnOnce(&T) -> &U,
@@ -249,11 +399,21 @@ impl<'a, T: ?Sized> Pin<&'a T> {
249399

250400
/// Gets a shared reference out of a pin.
251401
///
402+
/// This is safe because it is not possible to move out of a shared reference.
403+
/// It may seem like there is an issue here with interior mutability: in fact,
404+
/// it *is* possible to move a `T` out of a `&RefCell<T>`. However, this is
405+
/// not a problem as long as there does not also exist a `Pin<&T>` pointing
406+
/// to the same data, and `RefCell` does not let you create a pinned reference
407+
/// to its contents. See the discussion on ["pinning projections"] for further
408+
/// details.
409+
///
252410
/// Note: `Pin` also implements `Deref` to the target, which can be used
253411
/// to access the inner value. However, `Deref` only provides a reference
254412
/// that lives for as long as the borrow of the `Pin`, not the lifetime of
255413
/// the `Pin` itself. This method allows turning the `Pin` into a reference
256414
/// with the same lifetime as the original `Pin`.
415+
///
416+
/// ["pinning projections"]: ../../std/pin/index.html#projections-and-structural-pinning
257417
#[stable(feature = "pin", since = "1.33.0")]
258418
#[inline(always)]
259419
pub fn get_ref(self: Pin<&'a T>) -> &'a T {
@@ -306,13 +466,17 @@ impl<'a, T: ?Sized> Pin<&'a mut T> {
306466
///
307467
/// For example, if you wanted to get a `Pin` of a field of something,
308468
/// you could use this to get access to that field in one line of code.
469+
/// However, there are several gotchas with these "pinning projections";
470+
/// see the [`pin` module] documentation for further details on that topic.
309471
///
310472
/// # Safety
311473
///
312474
/// This function is unsafe. You must guarantee that the data you return
313475
/// will not move so long as the argument value does not move (for example,
314476
/// because it is one of the fields of that value), and also that you do
315477
/// not move out of the argument you receive to the interior function.
478+
///
479+
/// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
316480
#[stable(feature = "pin", since = "1.33.0")]
317481
pub unsafe fn map_unchecked_mut<U, F>(self: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
318482
F: FnOnce(&mut T) -> &mut U,

0 commit comments

Comments
 (0)