use std::{
borrow::Borrow,
fmt::Debug,
mem::ManuallyDrop,
ops::{Deref, DerefMut},
ptr::{self, NonNull},
};
use super::alloc::efree;
pub struct ZBox<T: ZBoxable>(NonNull<T>);
impl<T: ZBoxable> ZBox<T> {
pub unsafe fn from_raw(ptr: *mut T) -> Self {
Self(unsafe { NonNull::new_unchecked(ptr) })
}
#[expect(
clippy::expect_used,
reason = "the Zend allocator aborts the process on OOM, so the pointer is never null"
)]
pub(crate) unsafe fn from_zend_alloc(ptr: *mut T) -> Self {
Self(NonNull::new(ptr).expect("the Zend allocator returned a null pointer"))
}
#[must_use]
pub fn into_raw(self) -> *mut T {
ManuallyDrop::new(self).0.as_ptr()
}
}
impl<T: ZBoxable> Drop for ZBox<T> {
#[inline]
fn drop(&mut self) {
self.deref_mut().free();
}
}
impl<T: ZBoxable> Deref for ZBox<T> {
type Target = T;
#[inline]
fn deref(&self) -> &Self::Target {
unsafe { self.0.as_ref() }
}
}
impl<T: ZBoxable> DerefMut for ZBox<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Self::Target {
unsafe { self.0.as_mut() }
}
}
impl<T: ZBoxable + Debug> Debug for ZBox<T> {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
(**self).fmt(f)
}
}
impl<T: ZBoxable> Borrow<T> for ZBox<T> {
#[inline]
fn borrow(&self) -> &T {
self
}
}
impl<T: ZBoxable> AsRef<T> for ZBox<T> {
#[inline]
fn as_ref(&self) -> &T {
self
}
}
pub unsafe trait ZBoxable {
fn free(&mut self) {
unsafe { efree(ptr::from_mut(self).cast::<u8>()) };
}
}