Skip to content

Instantly share code, notes, and snippets.

@jpastuszek
Forked from rust-play/playground.rs
Last active April 25, 2023 13:52
Show Gist options
  • Save jpastuszek/f5f496bc71960e220b8332f8f0c549bf to your computer and use it in GitHub Desktop.
Save jpastuszek/f5f496bc71960e220b8332f8f0c549bf to your computer and use it in GitHub Desktop.
Pin and PhantomPinned
use core::pin::Pin;
use core::marker::PhantomPinned;
#[derive(Debug)]
struct Unm(i32, PhantomPinned); // !Unpin
//struct Unm(i32); // Unpin
fn foo() -> Pin<Box<Unm>> {
// PhantomPinned is !Unpin so Pin does not implement get_mut (disallowing mem::swap/replece and then move) nor into_inner (move out Unm of Box)
Box::pin(Unm(1, PhantomPinned))
// without PhantomPinned it is Unpin so Pin does allow for get_mut and into_inner making it mu
//Box::pin(Unm(1))
}
fn mv(u: Unm) {
drop(dbg![u])
}
// generic types don't implement Unpin, so Pin does not impl get_mut or into_inner
fn p<T>(mut pin: Pin<&mut T>) {
// E: the trait `Unpin` is not implemented for `T`
//let m: &mut T = pin.as_mut().get_mut();
}
fn main() {
{
let mut f = foo();
//let u: &mut Unm = f.as_mut().get_mut();
//let mut tmp: Unm = Unm(2);
//std::mem::swap(&mut tmp, u);
//mv(tmp); // moved u
}
{
let mut f = foo();
//let tmp = *Pin::into_inner(f);
//mv(tmp);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment