Last active
December 11, 2025 16:47
-
-
Save DarinM223/4dcedf432c07ffc55a1ccaab75a0221d to your computer and use it in GitHub Desktop.
Pin examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| extern crate pin_project_lite; // 0.2.16project; | |
| use pin_project_lite::pin_project; | |
| use std::marker::PhantomPinned; | |
| use std::pin::{Pin, pin}; | |
| use std::ptr::NonNull; | |
| pin_project! { | |
| #[derive(Debug)] | |
| pub struct A { | |
| #[pin] | |
| b: B, | |
| #[pin] | |
| c: C, | |
| _pin: PhantomPinned, | |
| } | |
| } | |
| #[derive(Debug)] | |
| pub struct B { | |
| c: NonNull<C>, | |
| data: i32, | |
| } | |
| impl B { | |
| pub fn set_c(&mut self, c: Pin<&mut C>) { | |
| self.c = NonNull::from(c.get_mut()); | |
| } | |
| pub fn c(&self) -> &C { | |
| unsafe { &*self.c.as_ptr() } | |
| } | |
| } | |
| #[derive(Debug)] | |
| pub struct C { | |
| b: NonNull<B>, | |
| data: String, | |
| } | |
| impl C { | |
| pub fn set_b(&mut self, b: Pin<&mut B>) { | |
| self.b = NonNull::from(b.get_mut()); | |
| } | |
| pub fn b(&self) -> &B { | |
| unsafe { &*self.b.as_ptr() } | |
| } | |
| } | |
| impl A { | |
| pub fn new() -> Pin<Box<Self>> { | |
| let mut a = Box::pin(A { | |
| b: B { | |
| c: NonNull::dangling(), | |
| data: 2, | |
| }, | |
| c: C { | |
| b: NonNull::dangling(), | |
| data: "hello".to_owned(), | |
| }, | |
| _pin: PhantomPinned, | |
| }); | |
| a.b.c = NonNull::from(&a.c); | |
| a.c.b = NonNull::from(&a.b); | |
| a | |
| } | |
| } | |
| fn main() { | |
| { | |
| let a = A::new(); | |
| println!("A: {a:?}"); | |
| println!("A's B's C: {:?}", a.b.c().data); | |
| println!("A's C's B: {:?}", a.c.b().data); | |
| let data = a.b.c().b().data; | |
| drop(a); | |
| println!("A's B's C's B: {:?}", data); | |
| } | |
| { | |
| let mut a = pin!(A { | |
| b: B { | |
| c: NonNull::dangling(), | |
| data: 2, | |
| }, | |
| c: C { | |
| b: NonNull::dangling(), | |
| data: "hello".to_owned(), | |
| }, | |
| _pin: PhantomPinned, | |
| }); | |
| let mut this = a.as_mut().project(); | |
| this.b.set_c(this.c.as_mut()); | |
| this.c.set_b(this.b.as_mut()); | |
| let data = a.b.c().b().data; | |
| println!("A's B's C's B: {:?}", data); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment