Skip to content

Commit

Permalink
Rollup merge of rust-lang#60165 - Nemo157:pin-into-inner, r=cramertj
Browse files Browse the repository at this point in the history
Add Pin::{into_inner,into_inner_unchecked}

These functions are useful for unsafe code that needs to temporarily pull smart pointers out of the `Pin`, e.g. [the change that inspired them](Nemo157/futures-rs@b436178#diff-1a4e0ba4d1b539412ca576411ec6c7c2R258) is taking a `Pin<Box<dyn Future>>`, turning it into a `*mut dyn Future` via `Box::into_raw(unsafe { Pin::into_inner_unchecked(pin) })` then later dropping this via `drop(Pin::from(Box::from_raw(ptr)))`. This can be accomplished today via `{ let ptr = unsafe { Pin::get_unchecked_mut(pin.as_mut()) } as *mut dyn Future; mem::forget(pin); ptr }`, but this is far more complicated and loses out on the symmetry of using `Box::into_raw` and `Box::from_raw`.

I'll extend the documentation on what guarantees `into_inner_unchecked` needs to uphold once I get some feedback on whether this API is wanted or not.

r? @withoutboats
  • Loading branch information
Centril authored Apr 25, 2019
2 parents 5c134f6 + a0e0849 commit 63adb5e
Showing 1 changed file with 34 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/libcore/pin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,18 @@ where
// around pinning.
unsafe { Pin::new_unchecked(pointer) }
}

/// Unwraps this `Pin<P>` returning the underlying pointer.
///
/// This requires that the data inside this `Pin` is [`Unpin`] so that we
/// can ignore the pinning invariants when unwrapping it.
///
/// [`Unpin`]: ../../std/marker/trait.Unpin.html
#[unstable(feature = "pin_into_inner", issue = "60245")]
#[inline(always)]
pub fn into_inner(pin: Pin<P>) -> P {
pin.pointer
}
}

impl<P: Deref> Pin<P> {
Expand Down Expand Up @@ -434,6 +446,28 @@ impl<P: Deref> Pin<P> {
pub fn as_ref(self: &Pin<P>) -> Pin<&P::Target> {
unsafe { Pin::new_unchecked(&*self.pointer) }
}

/// Unwraps this `Pin<P>` returning the underlying pointer.
///
/// # Safety
///
/// This function is unsafe. You must guarantee that you will continue to
/// treat the pointer `P` as pinned after you call this function, so that
/// the invariants on the `Pin` type can be upheld. If the code using the
/// resulting `P` does not continue to maintain the pinning invariants that
/// is a violation of the API contract and may lead to undefined behavior in
/// later (safe) operations.
///
/// If the underlying data is [`Unpin`], [`Pin::into_inner`] should be used
/// instead.
///
/// [`Unpin`]: ../../std/marker/trait.Unpin.html
/// [`Pin::into_inner`]: #method.into_inner
#[unstable(feature = "pin_into_inner", issue = "60245")]
#[inline(always)]
pub unsafe fn into_inner_unchecked(pin: Pin<P>) -> P {
pin.pointer
}
}

impl<P: DerefMut> Pin<P> {
Expand Down

0 comments on commit 63adb5e

Please sign in to comment.