#![allow(dead_code, deprecated, unused_variables, unused_mut)] #![feature(derive_coerce_pointee)] use std::marker::CoercePointee; use std::ops::Deref; use std::ptr::NonNull; #[derive(CoercePointee)] #[repr(transparent)] pub struct Rc { inner: NonNull>, } struct RcInner { refcount: usize, value: T, } impl Deref for Rc { type Target = T; fn deref(&self) -> &T { let ptr = self.inner.as_ptr(); unsafe { &(*ptr).value } } } impl Rc { pub fn new(value: T) -> Self { let inner = Box::new(RcInner { refcount: 1, value }); Self { inner: NonNull::from(Box::leak(inner)), } } } impl Clone for Rc { fn clone(&self) -> Self { unsafe { (*self.inner.as_ptr()).refcount += 1 }; Self { inner: self.inner } } } impl Drop for Rc { fn drop(&mut self) { let ptr = self.inner.as_ptr(); unsafe { (*ptr).refcount -= 1 }; if unsafe { (*ptr).refcount } == 0 { drop(unsafe { Box::from_raw(ptr) }); } } } fn main() {}