Created
August 25, 2018 20:42
-
-
Save rust-play/8ad88133bd0cbd35c22d76c7fe818133 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
This file contains 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
#![feature(pin)] | |
use std::marker::Unpin; | |
use std::ops::{Deref, DerefMut}; | |
use std::rc::Rc; | |
use std::sync::Arc; | |
#[derive(Copy, Clone)] | |
pub struct Pin<P> { | |
pointer: P, | |
} | |
impl<P> Deref for Pin<P> where | |
P: Deref, | |
{ | |
type Target = P::Target; | |
fn deref(&self) -> &P::Target { | |
&*self.pointer | |
} | |
} | |
impl<P> DerefMut for Pin<P> where | |
P: DerefMut, | |
P::Target: Unpin, | |
{ | |
fn deref_mut(&mut self) -> &mut P::Target { | |
&mut *self.pointer | |
} | |
} | |
impl<P> Pin<P> where | |
P: Deref, | |
{ | |
pub unsafe fn new_unchecked(pointer: P) -> Pin<P> { | |
Pin { pointer } | |
} | |
pub fn as_ref(this: &Pin<P>) -> Pin<&P::Target> { | |
Pin { pointer: &*this.pointer } | |
} | |
} | |
impl<P> Pin<P> where | |
P: DerefMut, | |
{ | |
pub fn as_mut(this: &mut Pin<P>) -> Pin<&mut P::Target> { | |
Pin { pointer: &mut *this.pointer } | |
} | |
pub unsafe fn get_mut_unchecked(&mut self) -> &mut P::Target { | |
&mut *self.pointer | |
} | |
} | |
impl<T> From<Box<T>> for Pin<Box<T>> { | |
fn from(pointer: Box<T>) -> Pin<Box<T>> { | |
unsafe { Pin::new_unchecked(pointer) } | |
} | |
} | |
pub unsafe trait Own: Deref + Sized where Self::Target: Sized { | |
fn own(data: Self::Target) -> Self; | |
fn pinned(data: Self::Target) -> Pin<Self> { | |
unsafe { Pin::new_unchecked(Self::own(data)) } | |
} | |
} | |
unsafe impl<T> Own for Box<T> { | |
fn own(data: T) -> Box<T> { | |
Box::new(data) | |
} | |
} | |
unsafe impl<T> Own for Rc<T> { | |
fn own(data: T) -> Rc<T> { | |
Rc::new(data) | |
} | |
} | |
unsafe impl<T> Own for Arc<T> { | |
fn own(data: T) -> Arc<T> { | |
Arc::new(data) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment