16
16
//! but doesn't allow moving `T`. The pointer value itself (the `Box`) can still be moved,
17
17
//! but the value behind it cannot.
18
18
//!
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`],
20
20
//! changing the location of the underlying data, [`Pin`] prohibits accessing the
21
21
//! underlying pointer type (the `&mut` or `Box`) directly, and provides its own set of
22
22
//! APIs for accessing and using the value. [`Pin`] also guarantees that no other
23
23
//! functions will move the pointed-to value. This allows for the creation of
24
24
//! self-references and other special behaviors that are only possible for unmovable
25
25
//! values.
26
26
//!
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 .
31
31
//!
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`
37
33
//!
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).
42
43
//!
43
44
//! # Examples
44
45
//!
94
95
//! // let new_unmoved = Unmovable::new("world".to_string());
95
96
//! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
96
97
//! ```
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
97
198
98
199
#![ stable( feature = "pin" , since = "1.33.0" ) ]
99
200
@@ -170,7 +271,12 @@ where
170
271
P :: Target : Unpin ,
171
272
{
172
273
/// 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
174
280
#[ stable( feature = "pin" , since = "1.33.0" ) ]
175
281
#[ inline( always) ]
176
282
pub fn new ( pointer : P ) -> Pin < P > {
@@ -191,15 +297,46 @@ impl<P: Deref> Pin<P> {
191
297
/// not guarantee that the data `P` points to is pinned, constructing a
192
298
/// `Pin<P>` is undefined behavior.
193
299
///
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
+ ///
194
323
/// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
195
324
/// instead.
325
+ ///
326
+ /// [`replace`]: ../../std/mem/fn.replace.html
196
327
#[ stable( feature = "pin" , since = "1.33.0" ) ]
197
328
#[ inline( always) ]
198
329
pub unsafe fn new_unchecked ( pointer : P ) -> Pin < P > {
199
330
Pin { pointer }
200
331
}
201
332
202
333
/// 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`.
203
340
#[ stable( feature = "pin" , since = "1.33.0" ) ]
204
341
#[ inline( always) ]
205
342
pub fn as_ref ( self : & Pin < P > ) -> Pin < & P :: Target > {
@@ -209,13 +346,22 @@ impl<P: Deref> Pin<P> {
209
346
210
347
impl < P : DerefMut > Pin < P > {
211
348
/// 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`.
212
355
#[ stable( feature = "pin" , since = "1.33.0" ) ]
213
356
#[ inline( always) ]
214
357
pub fn as_mut ( self : & mut Pin < P > ) -> Pin < & mut P :: Target > {
215
358
unsafe { Pin :: new_unchecked ( & mut * self . pointer ) }
216
359
}
217
360
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.
219
365
#[ stable( feature = "pin" , since = "1.33.0" ) ]
220
366
#[ inline( always) ]
221
367
pub fn set ( self : & mut Pin < P > , value : P :: Target )
@@ -227,17 +373,21 @@ impl<P: DerefMut> Pin<P> {
227
373
}
228
374
229
375
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.
231
377
///
232
378
/// For example, if you wanted to get a `Pin` of a field of something,
233
379
/// 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.
234
382
///
235
383
/// # Safety
236
384
///
237
385
/// This function is unsafe. You must guarantee that the data you return
238
386
/// will not move so long as the argument value does not move (for example,
239
387
/// because it is one of the fields of that value), and also that you do
240
388
/// not move out of the argument you receive to the interior function.
389
+ ///
390
+ /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
241
391
#[ stable( feature = "pin" , since = "1.33.0" ) ]
242
392
pub unsafe fn map_unchecked < U , F > ( self : Pin < & ' a T > , func : F ) -> Pin < & ' a U > where
243
393
F : FnOnce ( & T ) -> & U ,
@@ -249,11 +399,21 @@ impl<'a, T: ?Sized> Pin<&'a T> {
249
399
250
400
/// Gets a shared reference out of a pin.
251
401
///
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
+ ///
252
410
/// Note: `Pin` also implements `Deref` to the target, which can be used
253
411
/// to access the inner value. However, `Deref` only provides a reference
254
412
/// that lives for as long as the borrow of the `Pin`, not the lifetime of
255
413
/// the `Pin` itself. This method allows turning the `Pin` into a reference
256
414
/// with the same lifetime as the original `Pin`.
415
+ ///
416
+ /// ["pinning projections"]: ../../std/pin/index.html#projections-and-structural-pinning
257
417
#[ stable( feature = "pin" , since = "1.33.0" ) ]
258
418
#[ inline( always) ]
259
419
pub fn get_ref ( self : Pin < & ' a T > ) -> & ' a T {
@@ -306,13 +466,17 @@ impl<'a, T: ?Sized> Pin<&'a mut T> {
306
466
///
307
467
/// For example, if you wanted to get a `Pin` of a field of something,
308
468
/// 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.
309
471
///
310
472
/// # Safety
311
473
///
312
474
/// This function is unsafe. You must guarantee that the data you return
313
475
/// will not move so long as the argument value does not move (for example,
314
476
/// because it is one of the fields of that value), and also that you do
315
477
/// not move out of the argument you receive to the interior function.
478
+ ///
479
+ /// [`pin` module]: ../../std/pin/index.html#projections-and-structural-pinning
316
480
#[ stable( feature = "pin" , since = "1.33.0" ) ]
317
481
pub unsafe fn map_unchecked_mut < U , F > ( self : Pin < & ' a mut T > , func : F ) -> Pin < & ' a mut U > where
318
482
F : FnOnce ( & mut T ) -> & mut U ,
0 commit comments