1 //! Types which pin data to its location in memory
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.
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.
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.
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
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`.
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.
38 //! [`Pin`]: struct.Pin.html
39 //! [`Unpin`]: trait.Unpin.html
40 //! [`swap`]: ../../std/mem/fn.swap.html
41 //! [`Box`]: ../../std/boxed/struct.Box.html
48 //! use std::pin::Pin;
49 //! use std::marker::PhantomPinned;
50 //! use std::ptr::NonNull;
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 {
59 //! slice: NonNull<String>,
60 //! _pin: PhantomPinned,
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 {
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,
75 //! let mut boxed = Box::pinned(res);
77 //! let slice = NonNull::from(&boxed.data);
78 //! // we know this is safe because modifying a field doesn't move the whole struct
80 //! let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
81 //! Pin::get_mut_unchecked(mut_ref).slice = slice;
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));
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);
100 #![unstable(feature = "pin", issue = "49150")]
103 use marker::{Sized, Unpin};
104 use ops::{Deref, DerefMut, Receiver, CoerceUnsized, DispatchFromDyn};
106 /// A pinned pointer.
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`].
112 /// See the [`pin` module] documentation for further explanation on pinning.
114 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
115 /// [`pin` module]: ../../std/pin/index.html
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")]
122 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
127 impl<P: Deref> Pin<P>
131 /// Construct a new `Pin` around a pointer to some data of a type that
132 /// implements `Unpin`.
133 #[unstable(feature = "pin", issue = "49150")]
135 pub fn new(pointer: P) -> Pin<P> {
136 // Safety: the value pointed to is `Unpin`, and so has no requirements
138 unsafe { Pin::new_unchecked(pointer) }
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`.
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.
153 /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
155 #[unstable(feature = "pin", issue = "49150")]
157 pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
161 /// Get a pinned shared reference from this pinned pointer.
162 #[unstable(feature = "pin", issue = "49150")]
164 pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
165 unsafe { Pin::new_unchecked(&*self.pointer) }
169 impl<P: DerefMut> Pin<P> {
170 /// Get a pinned mutable reference from this pinned pointer.
171 #[unstable(feature = "pin", issue = "49150")]
173 pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
174 unsafe { Pin::new_unchecked(&mut *self.pointer) }
177 /// Assign a new value to the memory behind the pinned reference.
178 #[unstable(feature = "pin", issue = "49150")]
180 pub fn set(mut self: Pin<P>, value: P::Target)
184 *self.pointer = value;
188 impl<'a, T: ?Sized> Pin<&'a T> {
189 /// Construct a new pin by mapping the interior value.
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.
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
204 let pointer = &*self.pointer;
205 let new_pointer = func(pointer);
206 Pin::new_unchecked(new_pointer)
209 /// Get a shared reference out of a pin.
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")]
218 pub fn get_ref(self: Pin<&'a T>) -> &'a T {
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")]
227 pub fn into_ref(self: Pin<&'a mut T>) -> Pin<&'a T> {
228 Pin { pointer: self.pointer }
231 /// Get a mutable reference to the data inside of this `Pin`.
233 /// This requires that the data inside this `Pin` is `Unpin`.
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")]
242 pub fn get_mut(self: Pin<&'a mut T>) -> &'a mut T
248 /// Get a mutable reference to the data inside of this `Pin`.
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.
256 /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
258 #[unstable(feature = "pin", issue = "49150")]
260 pub unsafe fn get_unchecked_mut(self: Pin<&'a mut T>) -> &'a mut T {
264 /// Construct a new pin by mapping the interior value.
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.
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,
279 let pointer = Pin::get_unchecked_mut(self);
280 let new_pointer = func(pointer);
281 Pin::new_unchecked(new_pointer)
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))
293 #[unstable(feature = "pin", issue = "49150")]
294 impl<P: DerefMut> DerefMut for Pin<P>
298 fn deref_mut(&mut self) -> &mut P::Target {
299 Pin::get_mut(Pin::as_mut(self))
303 #[unstable(feature = "receiver_trait", issue = "0")]
304 impl<P: Receiver> Receiver for Pin<P> {}
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)
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)
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)
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>
338 #[unstable(feature = "pin", issue = "49150")]
339 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
341 P: DispatchFromDyn<U>,