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.
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`.
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.
35 //! [`Pin`]: struct.Pin.html
36 //! [`Unpin`]: trait.Unpin.html
37 //! [`swap`]: ../../std/mem/fn.swap.html
38 //! [`Box`]: ../../std/boxed/struct.Box.html
45 //! use std::pin::Pin;
46 //! use std::marker::Pinned;
47 //! use std::ptr::NonNull;
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 {
56 //! slice: NonNull<String>,
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 {
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(),
72 //! let mut boxed = Box::pinned(res);
74 //! let slice = NonNull::from(&boxed.data);
75 //! // we know this is safe because modifying a field doesn't move the whole struct
77 //! let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
78 //! Pin::get_mut_unchecked(mut_ref).slice = slice;
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));
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);
97 #![unstable(feature = "pin", issue = "49150")]
101 use ops::{Deref, DerefMut, CoerceUnsized, DispatchFromDyn};
104 pub use marker::Unpin;
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")]
121 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
126 impl<P: Deref> Pin<P>
130 /// Construct a new `Pin` around a pointer to some data of a type that
131 /// implements `Unpin`.
132 #[unstable(feature = "pin", issue = "49150")]
134 pub fn new(pointer: P) -> Pin<P> {
135 // Safety: the value pointed to is `Unpin`, and so has no requirements
137 unsafe { Pin::new_unchecked(pointer) }
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`.
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.
152 /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
154 #[unstable(feature = "pin", issue = "49150")]
156 pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
160 /// Get a pinned shared reference from this pinned pointer.
161 #[unstable(feature = "pin", issue = "49150")]
163 pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
164 unsafe { Pin::new_unchecked(&*self.pointer) }
168 impl<P: DerefMut> Pin<P> {
169 /// Get a pinned mutable reference from this pinned pointer.
170 #[unstable(feature = "pin", issue = "49150")]
172 pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
173 unsafe { Pin::new_unchecked(&mut *self.pointer) }
176 /// Assign a new value to the memory behind the pinned reference.
177 #[unstable(feature = "pin", issue = "49150")]
179 pub fn set(mut self: Pin<P>, value: P::Target)
183 *self.pointer = value;
187 impl<'a, T: ?Sized> Pin<&'a T> {
188 /// Construct a new pin by mapping the interior value.
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.
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
203 let pointer = &*this.pointer;
204 let new_pointer = func(pointer);
205 Pin::new_unchecked(new_pointer)
208 /// Get a shared reference out of a pin.
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")]
217 pub fn get_ref(this: Pin<&'a T>) -> &'a T {
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")]
226 pub fn into_ref(this: Pin<&'a mut T>) -> Pin<&'a T> {
227 Pin { pointer: this.pointer }
230 /// Get a mutable reference to the data inside of this `Pin`.
232 /// This requires that the data inside this `Pin` is `Unpin`.
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")]
241 pub fn get_mut(this: Pin<&'a mut T>) -> &'a mut T
247 /// Get a mutable reference to the data inside of this `Pin`.
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.
255 /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
257 #[unstable(feature = "pin", issue = "49150")]
259 pub unsafe fn get_mut_unchecked(this: Pin<&'a mut T>) -> &'a mut T {
263 /// Construct a new pin by mapping the interior value.
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.
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,
278 let pointer = Pin::get_mut_unchecked(this);
279 let new_pointer = func(pointer);
280 Pin::new_unchecked(new_pointer)
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))
292 #[unstable(feature = "pin", issue = "49150")]
293 impl<P: DerefMut> DerefMut for Pin<P>
297 fn deref_mut(&mut self) -> &mut P::Target {
298 Pin::get_mut(Pin::as_mut(self))
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)
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)
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)
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>
334 #[unstable(feature = "pin", issue = "49150")]
335 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
337 P: DispatchFromDyn<U>,
340 #[unstable(feature = "pin", issue = "49150")]
341 impl<P> Unpin for Pin<P> {}