Skip to content

Instantly share code, notes, and snippets.

@JoeyEremondi
Last active September 23, 2016 18:09
Show Gist options
  • Save JoeyEremondi/6c24dc04a3f5151e76959f7f67133387 to your computer and use it in GitHub Desktop.
Save JoeyEremondi/6c24dc04a3f5151e76959f7f67133387 to your computer and use it in GitHub Desktop.
use std::boxed::Box;
use std::rc::Rc;
use std::borrow::Borrow;
use std::mem;
struct BP_REF;
struct BP_BOX;
struct BP_OWNED;
struct BP_RC;
struct Ref<'a, T: 'a>(&'a T);
unsafe trait BorrowPlus<Borrowed: ?Sized, TRef>
: Borrow<Borrowed> + std::marker::Sized {
fn borrowPlusToRC(self) -> Rc<Borrowed>
where Self: BorrowPlus<Borrowed, BP_RC>
{
panic!("Impossible")
}
fn borrowPlusToOwned(self) -> Self
where Self: BorrowPlus<Borrowed, BP_OWNED>
{
panic!("Impossible")
}
fn borrowPlusToBox(self) -> Box<Borrowed>
where Self: BorrowPlus<Borrowed, BP_BOX>
{
panic!("Impossible")
}
}
unsafe impl<Borrowed> BorrowPlus<Borrowed, BP_RC> for Rc<Borrowed> {
fn borrowPlusToRC(self) -> Rc<Borrowed> {
self
}
}
unsafe impl<'a, Borrowed> BorrowPlus<Borrowed, BP_REF> for &'a Borrowed {}
unsafe impl<Borrowed> BorrowPlus<Borrowed, BP_BOX> for Box<Borrowed> {
fn borrowPlusToBox(self) -> Box<Borrowed> {
self
}
}
unsafe impl<Borrowed> BorrowPlus<Borrowed, BP_OWNED> for Borrowed {
fn borrowPlusToOwned(self) -> Borrowed {
self
}
}
fn asRc<T, BP: BorrowPlus<T, BP_RC>>(x: BP) -> Rc<T> {
x.borrowPlusToRC()
}
fn asBox<T, BP: BorrowPlus<T, BP_BOX>>(x: BP) -> Box<T> {
x.borrowPlusToBox()
}
fn main() {
let x = 3;
let y = &x;
// let z = asRc(y); //should not compile
let x = 3;
let y = Rc::new(x);
let z = asRc(y);
()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment