use ratatui_kit_macros::Props;
pub unsafe trait Props: Send + Sync {}
trait DropRaw {
fn drop_raw(&self, raw: *mut ());
}
struct DropRowImpl<T> {
_marker: std::marker::PhantomData<T>,
}
impl<T> DropRaw for DropRowImpl<T> {
fn drop_raw(&self, raw: *mut ()) {
unsafe {
let _ = Box::from_raw(raw as *mut T);
}
}
}
pub struct AnyProps<'a> {
raw: *mut (),
drop: Option<Box<dyn DropRaw + 'a>>,
_marker: std::marker::PhantomData<&'a mut ()>,
}
unsafe impl Send for AnyProps<'_> {}
unsafe impl Sync for AnyProps<'_> {}
impl<'a> AnyProps<'a> {
pub(crate) fn owned<T>(props: T) -> Self
where
T: Props + 'a,
{
let raw = Box::into_raw(Box::new(props));
Self {
raw: raw as *mut (),
drop: Some(Box::new(DropRowImpl::<T> {
_marker: std::marker::PhantomData,
})),
_marker: std::marker::PhantomData,
}
}
pub(crate) fn borrowed<T: Props>(props: &'a mut T) -> Self {
Self {
raw: props as *const _ as *mut (),
drop: None, _marker: std::marker::PhantomData,
}
}
pub(crate) fn borrow(&mut self) -> Self {
Self {
raw: self.raw,
drop: None,
_marker: std::marker::PhantomData,
}
}
pub(crate) unsafe fn downcast_ref_unchecked<T: Props>(&self) -> &T {
unsafe { &*(self.raw as *const T) }
}
pub(crate) unsafe fn downcast_mut_unchecked<T: Props>(&mut self) -> &mut T {
unsafe { &mut *(self.raw as *mut T) }
}
}
impl Drop for AnyProps<'_> {
fn drop(&mut self) {
if let Some(drop) = self.drop.take() {
drop.drop_raw(self.raw);
}
}
}
#[derive(Debug, Clone, Default, Props)]
pub struct NoProps;