]> git.lizzy.rs Git - rust.git/blob - src/libcore/pin.rs
Expand documantation for std::pin module
[rust.git] / src / libcore / pin.rs
1 //! Types which pin data to its location in memory
2 //!
3 //! It is sometimes useful to have objects that are guaranteed to not move,
4 //! in the sense that their placement in memory does not change, and can thus be relied upon.
5 //!
6 //! A prime example of such a scenario would be building self-referential structs,
7 //! since moving an object with pointers to itself will invalidate them,
8 //! which could cause undefined behavior.
9 //!
10 //! 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.
23 //!
24 //! However, these restrictions are usually not necessary. Many types are always freely
25 //! movable. These types implement the [`Unpin`] auto-trait, which nullifies the affect
26 //! of [`Pin`]. For `T: Unpin`, `Pin<Box<T>>` and `Box<T>` function identically, as do
27 //! `Pin<&mut T>` and `&mut T`.
28 //!
29 //! Note that pinning and `Unpin` only affect the pointed-to type. For example, whether
30 //! or not `Box<T>` is `Unpin` has no affect on the behavior of `Pin<Box<T>>`. Similarly,
31 //! `Pin<Box<T>>` and `Pin<&mut T>` are always `Unpin` themselves, even though the
32 //! `T` underneath them isn't, because the pointers in `Pin<Box<_>>` and `Pin<&mut _>`
33 //! are always freely movable, even if the data they point to isn't.
34 //!
35 //! [`Pin`]: struct.Pin.html
36 //! [`Unpin`]: trait.Unpin.html
37 //! [`swap`]: ../../std/mem/fn.swap.html
38 //! [`Box`]: ../../std/boxed/struct.Box.html
39 //!
40 //! # Examples
41 //!
42 //! ```rust
43 //! #![feature(pin)]
44 //!
45 //! use std::pin::Pin;
46 //! use std::marker::Pinned;
47 //! use std::ptr::NonNull;
48 //!
49 //! // This is a self-referential struct since the slice field points to the data field.
50 //! // We cannot inform the compiler about that with a normal reference,
51 //! // since this pattern cannot be described with the usual borrowing rules.
52 //! // Instead we use a raw pointer, though one which is known to not be null,
53 //! // since we know it's pointing at the string.
54 //! struct Unmovable {
55 //!     data: String,
56 //!     slice: NonNull<String>,
57 //!     _pin: Pinned,
58 //! }
59 //!
60 //! impl Unmovable {
61 //!     // To ensure the data doesn't move when the function returns,
62 //!     // we place it in the heap where it will stay for the lifetime of the object,
63 //!     // and the only way to access it would be through a pointer to it.
64 //!     fn new(data: String) -> Pin<Box<Self>> {
65 //!         let res = Unmovable {
66 //!             data,
67 //!             // we only create the pointer once the data is in place
68 //!             // otherwise it will have already moved before we even started
69 //!             slice: NonNull::dangling(),
70 //!             _pin: Pinned,
71 //!         };
72 //!         let mut boxed = Box::pinned(res);
73 //!
74 //!         let slice = NonNull::from(&boxed.data);
75 //!         // we know this is safe because modifying a field doesn't move the whole struct
76 //!         unsafe {
77 //!             let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
78 //!             Pin::get_mut_unchecked(mut_ref).slice = slice;
79 //!         }
80 //!         boxed
81 //!     }
82 //! }
83 //!
84 //! let unmoved = Unmovable::new("hello".to_string());
85 //! // The pointer should point to the correct location,
86 //! // so long as the struct hasn't moved.
87 //! // Meanwhile, we are free to move the pointer around.
88 //! # #[allow(unused_mut)]
89 //! let mut still_unmoved = unmoved;
90 //! assert_eq!(still_unmoved.slice, NonNull::from(&still_unmoved.data));
91 //!
92 //! // Since our type doesn't implement Unpin, this will fail to compile:
93 //! // let new_unmoved = Unmovable::new("world".to_string());
94 //! // std::mem::swap(&mut *still_unmoved, &mut *new_unmoved);
95 //! ```
96
97 #![unstable(feature = "pin", issue = "49150")]
98
99 use fmt;
100 use marker::Sized;
101 use ops::{Deref, DerefMut, CoerceUnsized, DispatchFromDyn};
102
103 #[doc(inline)]
104 pub use marker::Unpin;
105
106 /// A pinned pointer.
107 ///
108 /// This is a wrapper around a kind of pointer which makes that pointer "pin" its
109 /// value in place, preventing the value referenced by that pointer from being moved
110 /// unless it implements [`Unpin`].
111 ///
112 /// See the [`pin` module] documentation for further explanation on pinning.
113 ///
114 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
115 /// [`pin` module]: ../../std/pin/index.html
116 //
117 // Note: the derives below are allowed because they all only use `&P`, so they
118 // cannot move the value behind `pointer`.
119 #[unstable(feature = "pin", issue = "49150")]
120 #[fundamental]
121 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
122 pub struct Pin<P> {
123     pointer: P,
124 }
125
126 impl<P: Deref> Pin<P>
127 where
128     P::Target: Unpin,
129 {
130     /// Construct a new `Pin` around a pointer to some data of a type that
131     /// implements `Unpin`.
132     #[unstable(feature = "pin", issue = "49150")]
133     #[inline(always)]
134     pub fn new(pointer: P) -> Pin<P> {
135         // Safety: the value pointed to is `Unpin`, and so has no requirements
136         // around pinning.
137         unsafe { Pin::new_unchecked(pointer) }
138     }
139 }
140
141 impl<P: Deref> Pin<P> {
142     /// Construct a new `Pin` around a reference to some data of a type that
143     /// may or may not implement `Unpin`.
144     ///
145     /// # Safety
146     ///
147     /// This constructor is unsafe because we cannot guarantee that the data
148     /// pointed to by `pointer` is pinned. If the constructed `Pin<P>` does
149     /// not guarantee that the data `P` points to is pinned, constructing a
150     /// `Pin<P>` is undefined behavior.
151     ///
152     /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
153     /// instead.
154     #[unstable(feature = "pin", issue = "49150")]
155     #[inline(always)]
156     pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
157         Pin { pointer }
158     }
159
160     /// Get a pinned shared reference from this pinned pointer.
161     #[unstable(feature = "pin", issue = "49150")]
162     #[inline(always)]
163     pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
164         unsafe { Pin::new_unchecked(&*self.pointer) }
165     }
166 }
167
168 impl<P: DerefMut> Pin<P> {
169     /// Get a pinned mutable reference from this pinned pointer.
170     #[unstable(feature = "pin", issue = "49150")]
171     #[inline(always)]
172     pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
173         unsafe { Pin::new_unchecked(&mut *self.pointer) }
174     }
175
176     /// Assign a new value to the memory behind the pinned reference.
177     #[unstable(feature = "pin", issue = "49150")]
178     #[inline(always)]
179     pub fn set(mut self: Pin<P>, value: P::Target)
180     where
181         P::Target: Sized,
182     {
183         *self.pointer = value;
184     }
185 }
186
187 impl<'a, T: ?Sized> Pin<&'a T> {
188     /// Construct a new pin by mapping the interior value.
189     ///
190     /// For example, if you  wanted to get a `Pin` of a field of something,
191     /// you could use this to get access to that field in one line of code.
192     ///
193     /// # Safety
194     ///
195     /// This function is unsafe. You must guarantee that the data you return
196     /// will not move so long as the argument value does not move (for example,
197     /// because it is one of the fields of that value), and also that you do
198     /// not move out of the argument you receive to the interior function.
199     #[unstable(feature = "pin", issue = "49150")]
200     pub unsafe fn map_unchecked<U, F>(this: Pin<&'a T>, func: F) -> Pin<&'a U> where
201         F: FnOnce(&T) -> &U,
202     {
203         let pointer = &*this.pointer;
204         let new_pointer = func(pointer);
205         Pin::new_unchecked(new_pointer)
206     }
207
208     /// Get a shared reference out of a pin.
209     ///
210     /// Note: `Pin` also implements `Deref` to the target, which can be used
211     /// to access the inner value. However, `Deref` only provides a reference
212     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
213     /// the `Pin` itself. This method allows turning the `Pin` into a reference
214     /// with the same lifetime as the original `Pin`.
215     #[unstable(feature = "pin", issue = "49150")]
216     #[inline(always)]
217     pub fn get_ref(this: Pin<&'a T>) -> &'a T {
218         this.pointer
219     }
220 }
221
222 impl<'a, T: ?Sized> Pin<&'a mut T> {
223     /// Convert this `Pin<&mut T>` into a `Pin<&T>` with the same lifetime.
224     #[unstable(feature = "pin", issue = "49150")]
225     #[inline(always)]
226     pub fn into_ref(this: Pin<&'a mut T>) -> Pin<&'a T> {
227         Pin { pointer: this.pointer }
228     }
229
230     /// Get a mutable reference to the data inside of this `Pin`.
231     ///
232     /// This requires that the data inside this `Pin` is `Unpin`.
233     ///
234     /// Note: `Pin` also implements `DerefMut` to the data, which can be used
235     /// to access the inner value. However, `DerefMut` only provides a reference
236     /// that lives for as long as the borrow of the `Pin`, not the lifetime of
237     /// the `Pin` itself. This method allows turning the `Pin` into a reference
238     /// with the same lifetime as the original `Pin`.
239     #[unstable(feature = "pin", issue = "49150")]
240     #[inline(always)]
241     pub fn get_mut(this: Pin<&'a mut T>) -> &'a mut T
242         where T: Unpin,
243     {
244         this.pointer
245     }
246
247     /// Get a mutable reference to the data inside of this `Pin`.
248     ///
249     /// # Safety
250     ///
251     /// This function is unsafe. You must guarantee that you will never move
252     /// the data out of the mutable reference you receive when you call this
253     /// function, so that the invariants on the `Pin` type can be upheld.
254     ///
255     /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
256     /// instead.
257     #[unstable(feature = "pin", issue = "49150")]
258     #[inline(always)]
259     pub unsafe fn get_mut_unchecked(this: Pin<&'a mut T>) -> &'a mut T {
260         this.pointer
261     }
262
263     /// Construct a new pin by mapping the interior value.
264     ///
265     /// For example, if you  wanted to get a `Pin` of a field of something,
266     /// you could use this to get access to that field in one line of code.
267     ///
268     /// # Safety
269     ///
270     /// This function is unsafe. You must guarantee that the data you return
271     /// will not move so long as the argument value does not move (for example,
272     /// because it is one of the fields of that value), and also that you do
273     /// not move out of the argument you receive to the interior function.
274     #[unstable(feature = "pin", issue = "49150")]
275     pub unsafe fn map_unchecked_mut<U, F>(this: Pin<&'a mut T>, func: F) -> Pin<&'a mut U> where
276         F: FnOnce(&mut T) -> &mut U,
277     {
278         let pointer = Pin::get_mut_unchecked(this);
279         let new_pointer = func(pointer);
280         Pin::new_unchecked(new_pointer)
281     }
282 }
283
284 #[unstable(feature = "pin", issue = "49150")]
285 impl<P: Deref> Deref for Pin<P> {
286     type Target = P::Target;
287     fn deref(&self) -> &P::Target {
288         Pin::get_ref(Pin::as_ref(self))
289     }
290 }
291
292 #[unstable(feature = "pin", issue = "49150")]
293 impl<P: DerefMut> DerefMut for Pin<P>
294 where
295     P::Target: Unpin
296 {
297     fn deref_mut(&mut self) -> &mut P::Target {
298         Pin::get_mut(Pin::as_mut(self))
299     }
300 }
301
302 #[unstable(feature = "pin", issue = "49150")]
303 impl<P: fmt::Debug> fmt::Debug for Pin<P> {
304     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
305         fmt::Debug::fmt(&self.pointer, f)
306     }
307 }
308
309 #[unstable(feature = "pin", issue = "49150")]
310 impl<P: fmt::Display> fmt::Display for Pin<P> {
311     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
312         fmt::Display::fmt(&self.pointer, f)
313     }
314 }
315
316 #[unstable(feature = "pin", issue = "49150")]
317 impl<P: fmt::Pointer> fmt::Pointer for Pin<P> {
318     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
319         fmt::Pointer::fmt(&self.pointer, f)
320     }
321 }
322
323 // Note: this means that any impl of `CoerceUnsized` that allows coercing from
324 // a type that impls `Deref<Target=impl !Unpin>` to a type that impls
325 // `Deref<Target=Unpin>` is unsound. Any such impl would probably be unsound
326 // for other reasons, though, so we just need to take care not to allow such
327 // impls to land in std.
328 #[unstable(feature = "pin", issue = "49150")]
329 impl<P, U> CoerceUnsized<Pin<U>> for Pin<P>
330 where
331     P: CoerceUnsized<U>,
332 {}
333
334 #[unstable(feature = "pin", issue = "49150")]
335 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
336 where
337     P: DispatchFromDyn<U>,
338 {}
339
340 #[unstable(feature = "pin", issue = "49150")]
341 impl<P> Unpin for Pin<P> {}