Created
August 23, 2018 00:19
-
-
Save rust-play/4b4b3f7ea39e9668f2e21750a8c9a9b9 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, T> Deref for Pin<P> where | |
P: Deref<Target = T>, | |
{ | |
type Target = T; | |
fn deref(&self) -> &T { | |
&*self.pointer | |
} | |
} | |
impl<P, T> DerefMut for Pin<P> where | |
P: DerefMut<Target = T>, | |
T: Unpin, | |
{ | |
fn deref_mut(&mut self) -> &mut T { | |
&mut *self.pointer | |
} | |
} | |
impl<P> Pin<P> { | |
pub unsafe fn new_unchecked(pointer: P) -> Pin<P> { | |
Pin { pointer } | |
} | |
} | |
impl<P, T> Pin<P> where | |
P: Deref<Target = T>, | |
{ | |
pub fn as_ref(this: &Pin<P>) -> Pin<&T> { | |
Pin { pointer: &*this.pointer } | |
} | |
} | |
impl<P, T> Pin<P> where | |
P: DerefMut<Target = T>, | |
{ | |
pub fn as_mut(this: &mut Pin<P>) -> Pin<&mut T> { | |
Pin { pointer: &mut *this.pointer } | |
} | |
pub unsafe fn get_mut_unchecked(&mut self) -> &mut T { | |
&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