use core::fmt;
use core::marker::PhantomData;
use core::mem::{self, ManuallyDrop};
use core::ptr::NonNull;
use crate::ffi;
use crate::Message;
#[repr(transparent)]
#[derive(Debug)]
pub struct Allocated<T: ?Sized> {
ptr: NonNull<T>,
p: PhantomData<T>,
}
impl<T: Message + ?Sized> Allocated<T> {
#[inline]
pub(crate) unsafe fn new(ptr: *mut T) -> Option<Self> {
NonNull::new(ptr).map(|ptr| Self {
ptr,
p: PhantomData,
})
}
#[inline]
pub(crate) fn option_into_ptr(this: Option<Self>) -> *mut T {
let ptr = this.map(|this| ManuallyDrop::new(this).ptr);
unsafe { mem::transmute::<Option<NonNull<T>>, *mut T>(ptr) }
}
}
impl<T: ?Sized> Drop for Allocated<T> {
#[inline]
fn drop(&mut self) {
unsafe { ffi::objc_release(self.ptr.as_ptr().cast()) };
}
}
impl<T: ?Sized> fmt::Pointer for Allocated<T> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Pointer::fmt(&self.ptr.as_ptr(), f)
}
}