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 //! 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
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.
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.
28 //! [`Pin`]: struct.Pin.html
29 //! [`Unpin`]: trait.Unpin.html
30 //! [`swap`]: ../../std/mem/fn.swap.html
31 //! [`Box`]: ../../std/boxed/struct.Box.html
38 //! use std::pin::Pin;
39 //! use std::marker::Pinned;
40 //! use std::ptr::NonNull;
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 {
49 //! slice: NonNull<String>,
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 {
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(),
65 //! let mut boxed = Box::pinned(res);
67 //! let slice = NonNull::from(&boxed.data);
68 //! // we know this is safe because modifying a field doesn't move the whole struct
70 //! let mut_ref: Pin<&mut Self> = Pin::as_mut(&mut boxed);
71 //! Pin::get_mut_unchecked(mut_ref).slice = slice;
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));
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);
90 #![unstable(feature = "pin", issue = "49150")]
94 use ops::{Deref, DerefMut, CoerceUnsized, DispatchFromDyn};
97 pub use marker::Unpin;
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`].
105 /// See the [`pin` module] documentation for further explanation on pinning.
107 /// [`Unpin`]: ../../std/marker/trait.Unpin.html
108 /// [`pin` module]: ../../std/pin/index.html
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")]
114 #[derive(Copy, Clone, Hash, Eq, PartialEq, Ord, PartialOrd)]
119 impl<P: Deref> Pin<P>
123 /// Construct a new `Pin` around a pointer to some data of a type that
124 /// implements `Unpin`.
125 #[unstable(feature = "pin", issue = "49150")]
127 pub fn new(pointer: P) -> Pin<P> {
128 // Safety: the value pointed to is `Unpin`, and so has no requirements
130 unsafe { Pin::new_unchecked(pointer) }
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`.
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.
145 /// If `pointer` dereferences to an `Unpin` type, `Pin::new` should be used
147 #[unstable(feature = "pin", issue = "49150")]
149 pub unsafe fn new_unchecked(pointer: P) -> Pin<P> {
153 /// Get a pinned shared reference from this pinned pointer.
154 #[unstable(feature = "pin", issue = "49150")]
156 pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
157 unsafe { Pin::new_unchecked(&*self.pointer) }
161 impl<P: DerefMut> Pin<P> {
162 /// Get a pinned mutable reference from this pinned pointer.
163 #[unstable(feature = "pin", issue = "49150")]
165 pub fn as_mut(self: &mut Pin<P>) -> Pin<&mut P::Target> {
166 unsafe { Pin::new_unchecked(&mut *self.pointer) }
169 /// Assign a new value to the memory behind the pinned reference.
170 #[unstable(feature = "pin", issue = "49150")]
172 pub fn set(mut self: Pin<P>, value: P::Target)
176 *self.pointer = value;
180 impl<'a, T: ?Sized> Pin<&'a T> {
181 /// Construct a new pin by mapping the interior value.
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.
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
196 let pointer = &*this.pointer;
197 let new_pointer = func(pointer);
198 Pin::new_unchecked(new_pointer)
201 /// Get a shared reference out of a pin.
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")]
210 pub fn get_ref(this: Pin<&'a T>) -> &'a T {
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")]
219 pub fn into_ref(this: Pin<&'a mut T>) -> Pin<&'a T> {
220 Pin { pointer: this.pointer }
223 /// Get a mutable reference to the data inside of this `Pin`.
225 /// This requires that the data inside this `Pin` is `Unpin`.
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")]
234 pub fn get_mut(this: Pin<&'a mut T>) -> &'a mut T
240 /// Get a mutable reference to the data inside of this `Pin`.
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.
248 /// If the underlying data is `Unpin`, `Pin::get_mut` should be used
250 #[unstable(feature = "pin", issue = "49150")]
252 pub unsafe fn get_mut_unchecked(this: Pin<&'a mut T>) -> &'a mut T {
256 /// Construct a new pin by mapping the interior value.
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.
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,
271 let pointer = Pin::get_mut_unchecked(this);
272 let new_pointer = func(pointer);
273 Pin::new_unchecked(new_pointer)
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))
285 #[unstable(feature = "pin", issue = "49150")]
286 impl<P: DerefMut> DerefMut for Pin<P>
290 fn deref_mut(&mut self) -> &mut P::Target {
291 Pin::get_mut(Pin::as_mut(self))
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)
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)
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)
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>
327 #[unstable(feature = "pin", issue = "49150")]
328 impl<'a, P, U> DispatchFromDyn<Pin<U>> for Pin<P>
330 P: DispatchFromDyn<U>,
333 #[unstable(feature = "pin", issue = "49150")]
334 impl<P> Unpin for Pin<P> {}