use core::{borrow, fmt, hash, mem, ptr}; use loom::alloc; pub struct Box { ptr: *mut T, } impl Box { pub fn new(value: T) -> Self { let layout = alloc::Layout::new::(); let ptr = unsafe { alloc::alloc(layout) } as *mut T; unsafe { ptr::write(ptr, value) }; Self { ptr } } } impl Box { #[inline] pub fn into_raw(b: Box) -> *mut T { let ptr = b.ptr; mem::forget(b); ptr } pub const unsafe fn from_raw(ptr: *mut T) -> Box { Self { ptr } } } impl Drop for Box { fn drop(&mut self) { unsafe { let size = mem::size_of_val(&*self.ptr); let align = mem::align_of_val(&*self.ptr); let layout = alloc::Layout::from_size_align(size, align).unwrap(); ptr::drop_in_place(self.ptr); alloc::dealloc(self.ptr as *mut u8, layout); } } } unsafe impl Send for Box {} unsafe impl Sync for Box {} impl core::ops::Deref for Box { type Target = T; fn deref(&self) -> &T { unsafe { &*self.ptr } } } impl core::ops::DerefMut for Box { fn deref_mut(&mut self) -> &mut T { unsafe { &mut *self.ptr } } } impl borrow::Borrow for Box { fn borrow(&self) -> &T { &**self } } impl borrow::BorrowMut for Box { fn borrow_mut(&mut self) -> &mut T { &mut **self } } impl AsRef for Box { fn as_ref(&self) -> &T { &**self } } impl AsMut for Box { fn as_mut(&mut self) -> &mut T { &mut **self } } impl fmt::Display for Box { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Display::fmt(&**self, f) } } impl fmt::Debug for Box { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fmt::Debug::fmt(&**self, f) } } impl Clone for Box { #[inline] fn clone(&self) -> Box { Self::new(self.as_ref().clone()) } } impl PartialEq for Box { #[inline] fn eq(&self, other: &Box) -> bool { PartialEq::eq(&**self, &**other) } #[allow(clippy::partialeq_ne_impl)] #[inline] fn ne(&self, other: &Box) -> bool { PartialEq::ne(&**self, &**other) } } impl Eq for Box {} impl PartialOrd for Box { #[inline] fn partial_cmp(&self, other: &Box) -> Option { PartialOrd::partial_cmp(&**self, &**other) } #[inline] fn lt(&self, other: &Box) -> bool { PartialOrd::lt(&**self, &**other) } #[inline] fn le(&self, other: &Box) -> bool { PartialOrd::le(&**self, &**other) } #[inline] fn ge(&self, other: &Box) -> bool { PartialOrd::ge(&**self, &**other) } #[inline] fn gt(&self, other: &Box) -> bool { PartialOrd::gt(&**self, &**other) } } impl Ord for Box { #[inline] fn cmp(&self, other: &Box) -> core::cmp::Ordering { Ord::cmp(&**self, &**other) } } impl hash::Hash for Box { fn hash(&self, state: &mut H) { (**self).hash(state); } }