use std::{cell::UnsafeCell, fmt::Debug, any::Any};
use crate::tokens::TokenWith;
#[derive(Default)]
#[repr(transparent)]
pub struct Cell<T, const ID: usize> {
pub(crate) inner: UnsafeCell<T>,
}
unsafe impl<T: Send, const ID: usize> Send for Cell<T, ID> {}
unsafe impl<T: Send + Sync, const ID: usize> Sync for Cell<T, ID> {}
impl<T: Debug + Any, const ID: usize> Debug for Cell<T, ID> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Cell<{}, {}>", std::any::type_name::<T>(), ID)
}
}
impl<T, const ID: usize> Cell<T, ID> {
pub const fn new(t: T) -> Self {
Self {
inner: UnsafeCell::new(t),
}
}
pub fn from_mut(m: &mut T) -> &mut Self {
unsafe {std::mem::transmute(m)}
}
pub fn into_inner(self) -> T {
self.inner.into_inner()
}
pub fn as_ptr(&self) -> *const T {
self.inner.get()
}
pub unsafe fn get(&self) -> &T {
unsafe {std::mem::transmute(self)}
}
pub fn get_mut(&mut self) -> &mut T {
unsafe {std::mem::transmute(self)}
}
pub fn borrow<U>(&self, _: &TokenWith<U, ID>) -> &T {
unsafe {self.inner.get().as_ref().unwrap_unchecked()}
}
pub fn borrow_mut<U>(&self, _: &mut TokenWith<U, ID>) -> &mut T {
unsafe {self.inner.get().as_mut().unwrap_unchecked()}
}
}