#pin #macros #attribute

no-std pin-project

A crate for safe and ergonomic pin-projection

54 releases (2 stable)

new 1.0.1 Oct 15, 2020
1.0.0-alpha.1 Sep 22, 2020
0.4.27 Oct 11, 2020
0.4.23 Jul 27, 2020
0.3.2 Mar 30, 2019

#10 in Rust patterns

Download history 163210/week @ 2020-06-28 170777/week @ 2020-07-05 163438/week @ 2020-07-12 172702/week @ 2020-07-19 178490/week @ 2020-07-26 177414/week @ 2020-08-02 176631/week @ 2020-08-09 175036/week @ 2020-08-16 179490/week @ 2020-08-23 171247/week @ 2020-08-30 172607/week @ 2020-09-06 185072/week @ 2020-09-13 185376/week @ 2020-09-20 215107/week @ 2020-09-27 222585/week @ 2020-10-04 219498/week @ 2020-10-11

792,885 downloads per month
Used in 4,277 crates (185 directly)

Apache-2.0 OR MIT

64KB
292 lines

pin-project

crates-badge docs-badge license-badge rustc-badge

A crate for safe and ergonomic pin-projection.

Usage

Add this to your Cargo.toml:

[dependencies]
pin-project = "1"

The current pin-project requires Rust 1.37 or later.

Examples

#[pin_project] attribute creates projection types covering all the fields of struct or enum.

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
    }
}

code like this will be generated

To use #[pin_project] on enums, you need to name the projection type returned from the method.

use pin_project::pin_project;
use std::pin::Pin;

#[pin_project(project = EnumProj)]
enum Enum<T, U> {
    Pinned(#[pin] T),
    Unpinned(U),
}

impl<T, U> Enum<T, U> {
    fn method(self: Pin<&mut Self>) {
        match self.project() {
            EnumProj::Pinned(x) => {
                let _: Pin<&mut T> = x;
            }
            EnumProj::Unpinned(y) => {
                let _: &mut U = y;
            }
        }
    }
}

code like this will be generated

See documentation for more details, and see examples directory for more examples and generated code.

Related Projects

  • pin-project-lite: A lightweight version of pin-project written with declarative macros.

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~0.4–0.8MB
~21K SLoC