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