[−][src]Attribute Macro pin_project_internal::pin_project
#[pin_project]
An attribute that creates a projection type covering all the fields of struct or enum.
This attribute creates a projection type according to the following rules:
- For the field that uses
#[pin]
attribute, makes the pinned reference to the field. - For the other fields, makes the unpinned reference to the field.
And the following methods are implemented on the original #[pin_project]
type:
fn project(self: Pin<&mut Self>) -> Projection<'_>; fn project_ref(self: Pin<&Self>) -> ProjectionRef<'_>;
The visibility of the projected type and projection method is based on the original type.
However, if the visibility of the original type is pub
, the visibility of the projected type
and the projection method is downgraded to pub(crate)
.
Safety
This attribute is completely safe. In the absence of other unsafe
code that you write,
it is impossible to cause undefined behavior with this attribute.
This is accomplished by enforcing the four requirements for pin projection stated in the Rust documentation:
-
The struct must only be
Unpin
if all the structural fields areUnpin
.To enforce this, this attribute will automatically generate an
Unpin
implementation for you, which will require that all structurally pinned fields beUnpin
If you wish to provide an manualUnpin
impl, you can do so via theUnsafeUnpin
argument. -
The destructor of the struct must not move structural fields out of its argument.
To enforce this, this attribute will generate code like this:
struct MyStruct {} trait MyStructMustNotImplDrop {} impl<T: Drop> MyStructMustNotImplDrop for T {} impl MyStructMustNotImplDrop for MyStruct {}
If you attempt to provide an
Drop
impl, the blanket impl will then apply to your type, causing a compile-time error due to the conflict with the second impl.If you wish to provide a custom
Drop
impl, you can annotate a function with#[pinned_drop]
. This function takes a pinned version of your struct - that is,Pin
<&mut MyStruct>
whereMyStruct
is the type of your struct.You can call
project()
on this type as usual, along with any other methods you have defined. Because your code is never provided with a&mut MyStruct
, it is impossible to move out of pin-projectable fields in safe code in your destructor. -
You must make sure that you uphold the
Drop
guarantee: once your struct is pinned, the memory that contains the content is not overwritten or deallocated without calling the content's destructors.Safe code doesn't need to worry about this - the only wait to violate this requirement is to manually deallocate memory (which is
unsafe
), or to overwrite a field with something else. Because your custom destructor takesPin
<&mut MyStruct>
, it's impossible to obtain a mutable reference to a pin-projected field in safe code. -
You must not offer any other operations that could lead to data being moved out of the structural fields when your type is pinned.
As with requirement 3, it is impossible for safe code to violate this. This crate ensures that safe code can never obtain a mutable reference to
#[pin]
fields, which prevents you from ever moving out of them in safe code.
Pin projections are also incompatible with #[repr(packed)]
structs. Attempting to use this attribute
on a #[repr(packed)]
struct results in a compile-time error.
Examples
Using #[pin_project]
will automatically create the appropriate
conditional Unpin
implementation:
use pin_project::pin_project; use std::pin::Pin; #[pin_project] struct Struct<T, U> { #[pin] pinned: T, unpinned: U, } impl<T, U> Struct<T, U> { fn method(self: Pin<&mut Self>) { let this = self.project(); let _: Pin<&mut T> = this.pinned; // Pinned reference to the field let _: &mut U = this.unpinned; // Normal reference to the field } }
If you want to call the project()
method multiple times or later use the
original Pin
type, it needs to use .as_mut()
to avoid
consuming the Pin
.
Supported Items
#[pin_project]
can be used on structs and enums.
use pin_project::pin_project; use std::pin::Pin; #[pin_project] struct Struct<T, U> { #[pin] pinned: T, unpinned: U, } impl<T, U> Struct<T, U> { fn method(self: Pin<&mut Self>) { let this = self.project(); let _: Pin<&mut T> = this.pinned; let _: &mut U = this.unpinned; } }
use pin_project::pin_project; use std::pin::Pin; #[pin_project] struct TupleStruct<T, U>(#[pin] T, U); impl<T, U> TupleStruct<T, U> { fn method(self: Pin<&mut Self>) { let this = self.project(); let _: Pin<&mut T> = this.0; let _: &mut U = this.1; } }
#[pin_project]
supports enums, but to use it, you need to use with the
project
attribute.
The attribute at the expression position is not stable, so you need to use
a dummy project
attribute for the function.
use pin_project::{pin_project, project}; use std::pin::Pin; #[pin_project] enum Enum<T, U> { Tuple(#[pin] T), Struct { field: U }, Unit, } impl<T, U> Enum<T, U> { #[project] // Nightly does not need a dummy attribute to the function. fn method(self: Pin<&mut Self>) { #[project] match self.project() { Enum::Tuple(x) => { let _: Pin<&mut T> = x; } Enum::Struct { field } => { let _: &mut U = field; } Enum::Unit => {} } } }
See also project
and project_ref
attributes.
!Unpin
If you want to ensure that Unpin
is not implemented, use the !Unpin
argument to #[pin_project]
.
use pin_project::pin_project; #[pin_project(!Unpin)] struct Struct<T, U> { #[pin] pinned: T, unpinned: U, }
You can also ensure !Unpin
by using #[pin]
attribute for PhantomPinned
field.
use pin_project::pin_project; use std::marker::PhantomPinned; #[pin_project] struct Struct<T, U> { #[pin] pinned: T, unpinned: U, #[pin] _pin: PhantomPinned, }
Note that using PhantomPinned
without #[pin]
attribute has no effect.
UnsafeUnpin
If you want to implement Unpin
manually, you must use the UnsafeUnpin
argument to #[pin_project]
.
use pin_project::{pin_project, UnsafeUnpin}; #[pin_project(UnsafeUnpin)] struct Struct<T, U> { #[pin] pinned: T, unpinned: U, } unsafe impl<T: Unpin, U> UnsafeUnpin for Struct<T, U> {}
Note the usage of the unsafe UnsafeUnpin
trait, instead of the usual
Unpin
trait. UnsafeUnpin
behaves exactly like Unpin
, except that is
unsafe to implement. This unsafety comes from the fact that pin projections
are being used. If you implement UnsafeUnpin
, you must ensure that it is
only implemented when all pin-projected fields implement Unpin
.
See UnsafeUnpin
trait for more details.
#[pinned_drop]
In order to correctly implement pin projections, a type's Drop
impl must
not move out of any structurally pinned fields. Unfortunately, Drop::drop
takes &mut Self
, not Pin
<&mut Self>
.
To ensure that this requirement is upheld, the #[pin_project]
attribute will
provide a Drop
impl for you. This Drop
impl will delegate to an impl
block annotated with #[pinned_drop]
if you use the PinnedDrop
argument
to #[pin_project]
.
This impl block acts just like a normal Drop
impl,
except for the following two:
drop
method takesPin
<&mut Self>
- Name of the trait is
PinnedDrop
.
pub trait PinnedDrop { fn drop(self: Pin<&mut Self>); }
#[pin_project]
implements the actual Drop
trait via PinnedDrop
you
implemented. To drop a type that implements PinnedDrop
, use the drop
function just like dropping a type that directly implements Drop
.
In particular, it will never be called more than once, just like Drop::drop
.
For example:
use pin_project::{pin_project, pinned_drop}; use std::{fmt::Debug, pin::Pin}; #[pin_project(PinnedDrop)] struct Struct<T: Debug, U: Debug> { #[pin] pinned_field: T, unpin_field: U, } #[pinned_drop] impl<T: Debug, U: Debug> PinnedDrop for Struct<T, U> { fn drop(self: Pin<&mut Self>) { println!("Dropping pinned field: {:?}", self.pinned_field); println!("Dropping unpin field: {:?}", self.unpin_field); } } fn main() { let _x = Struct { pinned_field: true, unpin_field: 40 }; }
See also pinned_drop
attribute.
project_replace()
In addition to the project()
and project_ref()
methods which are always
provided when you use the #[pin_project]
attribute, there is a third method,
project_replace()
which can be useful in some situations. It is equivalent
to Pin::set
, except that the unpinned fields are moved and returned,
instead of being dropped in-place.
fn project_replace(self: Pin<&mut Self>, other: Self) -> ProjectionOwned;
The ProjectionOwned
type is identical to the Self
type, except that
all pinned fields have been replaced by equivalent PhantomData
types.
This method is opt-in, because it is only supported for Sized
types, and
because it is incompatible with the #[pinned_drop]
attribute described
above. It can be enabled by using #[pin_project(Replace)]
.
For example:
use pin_project::{pin_project, project_replace}; #[pin_project(Replace)] enum Struct<T> { A { #[pin] pinned_field: i32, unpinned_field: T, }, B, } #[project_replace] fn main() { let mut x = Box::pin(Struct::A { pinned_field: 42, unpinned_field: "hello" }); #[project_replace] match x.as_mut().project_replace(Struct::B) { Struct::A { unpinned_field, .. } => assert_eq!(unpinned_field, "hello"), Struct::B => unreachable!(), } }
The project_replace
attributes are necessary whenever destructuring the return
type of project_replace()
, and work in exactly the same way as the
project
and project_ref
attributes.