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