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