-
-
Save tmccombs/7ea71f48a935f258837f038621f07b83 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
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
#![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) | |
} | |
} | |
impl<T> From<Vec<T>> for Pin<Vec<T>> { | |
fn from(pointer: Vec<T>) -> Pin<Vec<T>> { | |
unsafe { Pin::new_unchecked(pointer) } | |
} | |
} | |
impl<P, T> Pin<P> | |
where | |
P: DerefMut<Target = [T]>, | |
{ | |
pub fn index_pin<'a, I>(&'a mut self, idx: I) -> Pin<&'a mut I::Output> | |
where | |
I: SliceIndex<[T]>, | |
T: 'a | |
{ | |
unsafe {Pin::new_unchecked(&mut self.pointer[idx]) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment