use std::cell::{Ref, RefCell, RefMut};
use std::mem::ManuallyDrop;
use std::thread::LocalKey;
pub struct UiCell<T>(RefCell<ManuallyDrop<T>>);
impl<T> UiCell<T> {
pub const fn new(value: T) -> Self {
Self(RefCell::new(ManuallyDrop::new(value)))
}
pub fn borrow(&self) -> Ref<'_, T> {
Ref::map(self.0.borrow(), |v| &**v)
}
pub fn borrow_mut(&self) -> RefMut<'_, T> {
RefMut::map(self.0.borrow_mut(), |v| &mut **v)
}
pub fn try_borrow(&self) -> Result<Ref<'_, T>, std::cell::BorrowError> {
self.0.try_borrow().map(|r| Ref::map(r, |v| &**v))
}
pub fn try_borrow_mut(&self) -> Result<RefMut<'_, T>, std::cell::BorrowMutError> {
self.0.try_borrow_mut().map(|r| RefMut::map(r, |v| &mut **v))
}
}
pub trait UiLocal<T: 'static> {
fn with_borrow<R>(&'static self, f: impl FnOnce(&T) -> R) -> R;
fn with_borrow_mut<R>(&'static self, f: impl FnOnce(&mut T) -> R) -> R;
fn set(&'static self, value: T);
fn take(&'static self) -> T
where
T: Default;
fn replace(&'static self, value: T) -> T;
}
impl<T: 'static> UiLocal<T> for LocalKey<UiCell<T>> {
fn with_borrow<R>(&'static self, f: impl FnOnce(&T) -> R) -> R {
self.with(|c| f(&c.borrow()))
}
fn with_borrow_mut<R>(&'static self, f: impl FnOnce(&mut T) -> R) -> R {
self.with(|c| f(&mut c.borrow_mut()))
}
fn set(&'static self, value: T) {
drop(self.replace(value));
}
fn take(&'static self) -> T
where
T: Default,
{
self.replace(T::default())
}
fn replace(&'static self, value: T) -> T {
self.with(|c| std::mem::replace(&mut *c.borrow_mut(), value))
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn has_no_destructor() {
assert!(!std::mem::needs_drop::<UiCell<Vec<String>>>());
}
#[test]
fn reachable_while_the_thread_exits() {
struct Reaches;
impl Drop for Reaches {
fn drop(&mut self) {
COUNT.with_borrow_mut(|c| c.push(1));
}
}
thread_local! {
static HOLDER: RefCell<Option<Reaches>> = const { RefCell::new(None) };
static COUNT: UiCell<Vec<u32>> = const { UiCell::new(Vec::new()) };
}
let exited = std::thread::spawn(|| {
HOLDER.with_borrow_mut(|_| ());
COUNT.with_borrow_mut(|c| c.push(0));
HOLDER.with_borrow_mut(|h| *h = Some(Reaches));
})
.join();
assert!(exited.is_ok());
}
}