Skip to content

Instantly share code, notes, and snippets.

@narodnik
Created April 30, 2020 08:39
Show Gist options
  • Save narodnik/d7c1157ed4ea1021918fd18e10b09284 to your computer and use it in GitHub Desktop.
Save narodnik/d7c1157ed4ea1021918fd18e10b09284 to your computer and use it in GitHub Desktop.
#![feature(pin, arbitrary_self_types, optin_builtin_traits)]
use std::ptr;
use std::mem::Pin;
use std::boxed::PinBox;
use std::marker::Unpin;
struct SelfReferential {
data: i32,
self_ref: *const i32,
}
impl !Unpin for SelfReferential {}
impl SelfReferential {
fn new() -> SelfReferential {
SelfReferential { data: 42, self_ref: ptr::null() }
}
fn init(mut self: Pin<SelfReferential>) {
let this : &mut SelfReferential = unsafe { Pin::get_mut(&mut self) };
// Set up self_ref to point to this.data.
this.self_ref = &this.data as *const i32;
}
fn read_ref(self: Pin<SelfReferential>) -> Option<i32> {
let this : &SelfReferential = &*self;
// Dereference self_ref if it is non-NULL.
if this.self_ref == ptr::null() {
None
} else {
Some(unsafe { *this.self_ref })
}
}
}
fn main() {
let mut s = PinBox::new(SelfReferential::new());
s.as_pin().init();
println!("{:?}", s.as_pin().read_ref()); // prints Some(42)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment