What is Pin and why we need that
the idea behind Pin is the moment you place something in a pin you are promising that you will not move it again. that’s said if you have a Pin, you can’t get mutable reference to the type behind it unless you promise you won’t move it.
为什么需要Pin?
假如我们需要实现一个parser,这个parser从str 解析出token,但我们不希望这个parser和str有引用关系,我们希望是一个ownedParser,这里我们希望Parsed reference buf, 但这里Parsed的lifetime无法指定,因为这里Parsed实际上引用了自己,称为 self referential.
struct OwnedParser {
buf: Vec<u8>,
parsed: Parsed<'lifetimeOfBuf>
}
struct Parsed<'a> {
token: &'a [u8]
}
假设rust允许我们自引用,这里,parsed中包含了一个指向buf的引用,这样会有什么问题吗?
let a = OwnedParser::new("str");
let b = a;
如果 a
发生了move, 会出现什么情况?
在之前的文章中介绍过move的本质其实就是一次memcpy,当a move 到b后,buf被copy到新的内存,但是parsed指向的仍然是 a 的buf,这样就造成b的parsed字段所指向的buf是一个非法地址。
What actually Move is
Pin
为了解决或者说绕过这个问题,出现了Pin以及Unpin, Pin是一个struct,Unpin是一个trait
pub struct Pin<P> {
pointer: P,
}
pub auto trait Unpin {}
可以通过Pin::new() 构造一个Pin对象,将目标指针包在Pin中,但实际上Pin并没有魔法可以阻止目标对象发生move或者通过mem::replace替换,它能做的是阻止调用者访问到目标对象 T
例如这段代码,实际上,你无法防止s发生move
let mut s = "this".to_string();
let mut pinned_string = Pin::new(&mut s);
let s2 = s;
所以tokio提供了一个宏 pin! 用来将原变量覆盖
let mut s = "this".to_string();
tokio::pin!(s);
这里s就变成了 Pin<&mut String>
然而,看了文档后,我发现即使在pin后,任然可以通过 pin::get_mut() 拿到原变量的mut ref,那不是任然可以在pin之后修改原变量吗?
仔细看get_mut的参数,发现 T:Unpin, Unpin 又是个什么?
Unpin
Types that can be safely moved after being pinned. This trait is automatically implemented for almost every type.
Unpin是一个autotrait,基本上所有的类型都实现了Unpin,除非你主动实现 !Unpin, 或者你的结构体中有一个字段是 !Unpin, 或者,这个struct中包含 PhantomPinned类型字段。那么什么是一个 !Unpin的类型?
包含一个自引用字段的类型就是!Unpin, 所有的async函数在编译后都会实现!Unpin。
当T是!Unpin类型的时候,就只能通过 get_unchecked_mut 来拿到mut ref,注意这是一个unsafe的函数,也就是说编译器需要你自己保证不会在拿到mut ref后,做一些危险的事情。
Async
那这和async await 有什么关系呢?为什么poll要求 FooFuture pin呢?
struct FooFuture;
impl Future for FooFuture {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
todo!()
}
}
这和async await的实现有关
Pinning
pin_project
当我们需要实现一个future的时候,我们通常会需要包装另一个future,例如
struct MySleep {
sleep: tokio::time::Sleep
}
impl Future for MySleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
self.sleep.poll(cx)
}
}
error[E0599]: no method named `poll` found for struct `Sleep` in the current scope
--> src/main.rs:69:20
|
69 | self.sleep.poll(cx)
| ^^^^ method not found in `Sleep`
|
::: /Users/sean/.rustup/toolchains/stable-x86_64-apple-darwin/lib/rustlib/src/rust/library/core/src/future/future.rs:99:8
编译失败,并不能直接poll sleep, 因为sleep不是Pin类型的,那直接Pin::new() 试试?
impl Future for MySleep {
type Output = ();
fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
Pin::new(&mut self.sleep).poll(cx)
}
}
error[E0277]: `PhantomPinned` cannot be unpinned
--> src/main.rs:69:9
|
69 | Pin::new(&mut self.sleep).poll(cx)
| ^^^^^^^^ within `tokio::time::driver::sleep::_::__Origin<'_>`, the trait `Unpin` is not implemented for `PhantomPinned`
|
= note: consider using `Box::pin`
= note: required because it appears within the type `tokio::time::driver::entry::TimerEntry`
= note: required because it appears within the type `tokio::time::driver::sleep::_::__Origin<'_>`
= note: required because of the requirements on the impl of `Unpin` for `Sleep`
note: required by `Pin::<P>::new`
仍然不行,因为Sleep类型中有个PhantomPinned,导致Sleep是!Unpin的,那就只能unsafe了
impl Future for MySleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
unsafe {
let this = self.get_unchecked_mut();
Pin::new_unchecked(&mut this.sleep).poll(cx)
}
}
}
这回编译通过了,但显然unsafe让人看着很不舒服,所以通常会用pin_project这个crate来对struct进行封装
#[pin_project]
struct MySleep {
#[pin]
sleep: tokio::time::Sleep
}
impl Future for MySleep {
type Output = ();
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let mut this = self.project();
this.sleep.as_mut().poll(cx)
}
}
通过cargo expand将宏展开,可以看到,pin_project生成的代码
cargo expand 需要用rust +nightly 执行
#[allow(unused_extern_crates)]
extern crate pin_project as _pin_project;
#[allow(dead_code)]
#[allow(clippy::mut_mut)]
struct __MySleepProjection<'pin> // 通过project() 返回一个新的 __MySleepProjection 类型
where
MySleep: 'pin, // 这里没看懂,MySleep: 'pin 代表什么意思?
{
sleep: ::pin_project::__private::Pin<&'pin mut (tokio::time::Sleep)>,
}
#[allow(dead_code)]
#[allow(clippy::ref_option_ref)]
struct __MySleepProjectionRef<'pin> // 通过 prject_ref() 返回的类型
where
MySleep: 'pin,
{
sleep: ::pin_project::__private::Pin<&'pin (tokio::time::Sleep)>,
}
impl MySleep {
fn project<'pin>(
self: _pin_project::__private::Pin<&'pin mut Self>,
) -> __MySleepProjection<'pin> {
unsafe {
let Self { sleep } = self.get_unchecked_mut(); // 通过unchecked_mut() 返回 sleep mut ref
__MySleepProjection {
sleep: _pin_project::__private::Pin::new_unchecked(sleep), // 返回project类型
}
}
}
#[allow(clippy::missing_const_for_fn)]
fn project_ref<'pin>(
self: _pin_project::__private::Pin<&'pin Self>,
) -> __MySleepProjectionRef<'pin> {
unsafe {
let Self { sleep } = self.get_ref();
__MySleepProjectionRef {
sleep: _pin_project::__private::Pin::new_unchecked(sleep),
}
}
}
}
// Ensure that it's impossible to use pin projections on a #[repr(packed)]
#[forbid(unaligned_references, safe_packed_borrows)]
fn __assert_not_repr_packed(this: &MySleep) {
let _ = &this.sleep;
}
// 这个自动生成的结构体,目的是为了为MySleep自动impl Unpin
// impl<T, U> Unpin for Struct<T, U> where T: Unpin {}
// However, if struct is public and there is a private type field,
// this would cause an E0446 (private type in public interface).
//
// When RFC 2145 is implemented (rust-lang/rust#48054),
// this will become a lint, rather then a hard error.
//
// As a workaround for this, we generate a new struct, containing all of
// the pinned fields from our #[pin_project] type. This struct is declared
// within a function, which makes it impossible to be named by user code.
// This guarantees that it will use the default auto-trait impl for Unpin -
// that is, it will implement Unpin iff all of its fields implement Unpin.
// This type can be safely declared as 'public', satisfying the privacy
// checker without actually allowing user code to access it.
//
// This allows users to apply the #[pin_project] attribute to types
// regardless of the privacy of the types of their fields.
#[allow(missing_debug_implementations)]
struct __MySleep<'pin> {
__pin_project_use_generics: _pin_project::__private::AlwaysUnpin<'pin, ()>,
__field0: tokio::time::Sleep,
}
impl<'pin> _pin_project::__private::Unpin for MySleep where
__MySleep<'pin>: _pin_project::__private::Unpin
{
}
#[doc(hidden)]
unsafe impl<'pin> _pin_project::UnsafeUnpin for MySleep where
__MySleep<'pin>: _pin_project::__private::Unpin
{
}
trait MySleepMustNotImplDrop {}
#[allow(clippy::drop_bounds, drop_bounds)]
impl<T: _pin_project::__private::Drop> MySleepMustNotImplDrop for T {}
impl MySleepMustNotImplDrop for MySleep {}
#[doc(hidden)]
impl _pin_project::__private::PinnedDrop for MySleep {
unsafe fn drop(self: _pin_project::__private::Pin<&mut Self>) {}
}
Pin>
Box is a pointer, it makes sure that it has a stable location, and pin makes sure that you will never be able to move T unless it’s unpin (you can never get mutable reference to T),
Pin<Box>
is a way to get things that are !Unpin to Unpin.
也可以通过Box将sleep包起来,因为无论T是否是Unpin,Box
struct MySleep {
sleep: Pin<Box<tokio::time::Sleep>>
}
总结
Pin的作用实际上并不是把内存pin住,而是不让你轻松的拿到 &mut T, 这样你就不能去替换或者move T,仅此而已