use { crate::utils::{ linkedlist::NodeRef, ptr_ext::{MutPtrExt, PtrExt}, }, jay_config::keyboard::mods::Modifiers, std::{ cell::UnsafeCell, fmt::{Debug, Formatter}, mem, rc::{Rc, Weak}, }, }; pub struct CloneCell { data: UnsafeCell, } impl Clone for CloneCell { fn clone(&self) -> Self { Self { data: UnsafeCell::new(self.get()), } } } impl Debug for CloneCell { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { self.get().fmt(f) } } impl CloneCell { pub const fn new(t: T) -> Self { Self { data: UnsafeCell::new(t), } } #[inline(always)] pub fn get(&self) -> T where T: UnsafeCellCloneSafe, { unsafe { self.data.get().deref().clone() } } #[inline(always)] pub fn set(&self, t: T) -> T { unsafe { mem::replace(self.data.get().deref_mut(), t) } } #[inline(always)] pub fn take(&self) -> T where T: Default, { self.set(T::default()) } } impl Default for CloneCell { fn default() -> Self { Self::new(Default::default()) } } pub unsafe trait UnsafeCellCloneSafe: Clone {} unsafe impl UnsafeCellCloneSafe for Option {} unsafe impl UnsafeCellCloneSafe for Rc {} unsafe impl UnsafeCellCloneSafe for Weak {} unsafe impl UnsafeCellCloneSafe for NodeRef {} unsafe impl UnsafeCellCloneSafe for () {} unsafe impl UnsafeCellCloneSafe for u64 {} unsafe impl UnsafeCellCloneSafe for i32 {} unsafe impl UnsafeCellCloneSafe for (A, B) {} unsafe impl UnsafeCellCloneSafe for Modifiers {}