initial global widget store
This commit is contained in:
@@ -1,28 +1,34 @@
|
||||
use std::{
|
||||
cell::{Ref, RefCell, RefMut},
|
||||
any::{Any, TypeId},
|
||||
marker::Unsize,
|
||||
ops::CoerceUnsized,
|
||||
rc::{Rc, Weak},
|
||||
sync::{Arc, Mutex, Weak},
|
||||
};
|
||||
|
||||
pub struct Handle<T: ?Sized>(Rc<RefCell<T>>);
|
||||
pub struct WeakHandle<T: ?Sized>(Weak<RefCell<T>>);
|
||||
pub struct Handle<T: ?Sized>(Arc<Mutex<T>>);
|
||||
pub struct WeakHandle<T: ?Sized>(Weak<Mutex<T>>);
|
||||
|
||||
pub type Ref<'a, T> = std::sync::MutexGuard<'a, T>;
|
||||
pub type RefMut<'a, T> = std::sync::MutexGuard<'a, T>;
|
||||
|
||||
pub type RefMap<'a, T> = std::sync::MappedMutexGuard<'a, T>;
|
||||
pub type RefMapMut<'a, T> = std::sync::MappedMutexGuard<'a, T>;
|
||||
|
||||
impl<T: ?Sized> Handle<T> {
|
||||
pub fn get(&self) -> Ref<'_, T> {
|
||||
self.0.borrow()
|
||||
self.0.lock().unwrap()
|
||||
}
|
||||
|
||||
pub fn get_mut(&self) -> RefMut<'_, T> {
|
||||
self.0.borrow_mut()
|
||||
self.0.lock().unwrap()
|
||||
}
|
||||
|
||||
pub fn refs(&self) -> usize {
|
||||
Rc::strong_count(&self.0)
|
||||
Arc::strong_count(&self.0)
|
||||
}
|
||||
|
||||
pub fn weak(&self) -> WeakHandle<T> {
|
||||
WeakHandle(Rc::downgrade(&self.0))
|
||||
WeakHandle(Arc::downgrade(&self.0))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +36,21 @@ impl<T: ?Sized> WeakHandle<T> {
|
||||
pub fn strong(&self) -> Option<Handle<T>> {
|
||||
Some(Handle(self.0.upgrade()?))
|
||||
}
|
||||
|
||||
pub fn dropped(&self) -> bool {
|
||||
self.0.strong_count() == 0
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// you must guarantee the type outside
|
||||
pub unsafe fn downcast<U: 'static>(self) -> Option<WeakHandle<U>>
|
||||
where
|
||||
T: 'static,
|
||||
{
|
||||
let raw: *const Mutex<T> = self.0.into_raw();
|
||||
let raw: *const Mutex<U> = raw.cast();
|
||||
Some(WeakHandle(unsafe { Weak::from_raw(raw) }))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T: ?Sized> Clone for Handle<T> {
|
||||
@@ -52,7 +73,7 @@ impl<T: Default> Default for Handle<T> {
|
||||
|
||||
impl<T> From<T> for Handle<T> {
|
||||
fn from(value: T) -> Self {
|
||||
Self(Rc::new(RefCell::new(value)))
|
||||
Self(Arc::new(Mutex::new(value)))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user