use alloc::vec::Vec;
use core::{
ops::{Deref, DerefMut},
ptr::NonNull,
};
pub(crate) struct CBox<T: ?Sized> {
ptr: NonNull<T>,
}
impl<T: ?Sized> CBox<T> {
pub(crate) unsafe fn new(ptr: *mut T) -> Self {
CBox {
ptr: NonNull::new_unchecked(ptr),
}
}
pub(crate) fn as_ptr(&self) -> *mut T {
self.ptr.as_ptr()
}
pub(crate) fn as_ref(&self) -> &T {
unsafe { self.ptr.as_ref() }
}
pub(crate) fn as_mut(&mut self) -> &mut T {
unsafe { self.ptr.as_mut() }
}
}
impl<T: ?Sized> Deref for CBox<T> {
type Target = T;
fn deref(&self) -> &T {
self.as_ref()
}
}
impl<T: ?Sized> DerefMut for CBox<T> {
fn deref_mut(&mut self) -> &mut T {
self.as_mut()
}
}
impl<T: Clone> CBox<[T]> {
pub(crate) fn clone_slice(&self) -> Vec<T> {
self.as_ref().into()
}
}
impl<T: ?Sized> Drop for CBox<T> {
fn drop(&mut self) {
unsafe {
libc::free(self.as_ptr() as *mut libc::c_void);
}
}
}