use alloc::{boxed::Box, collections::BTreeMap, rc::Rc, vec::Vec};
use core::{
any::{Any, TypeId, type_name},
cell::RefCell,
fmt::Debug,
num::NonZeroUsize,
};
use crate::observe::{self, Origin};
#[derive(Debug, Default, Clone)]
pub struct Metadata(Box<MetadataInner>);
#[derive(Debug, Default, Clone)]
struct MetadataInner(BTreeMap<TypeId, Rc<dyn Any>>);
impl MetadataInner {
pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
self.0
.get(&TypeId::of::<T>())
.and_then(|value| value.downcast_ref::<T>())
.cloned()
}
pub fn insert<T: 'static + Clone>(&mut self, value: T) {
self.0.insert(TypeId::of::<T>(), Rc::new(value));
}
}
pub type Watcher<T> = Rc<dyn Fn(Context<T>) + 'static>;
#[derive(Debug, Clone)]
pub struct Context<T> {
value: T,
metadata: Metadata,
}
impl<T> Context<T> {
pub const fn new(value: T, metadata: Metadata) -> Self {
Self { value, metadata }
}
#[must_use]
pub fn with<V: Clone + 'static>(mut self, value: V) -> Self {
self.metadata = self.metadata.with(value);
self
}
pub fn into_value(self) -> T {
self.value
}
pub const fn value(&self) -> &T {
&self.value
}
pub const fn value_mut(&mut self) -> &mut T {
&mut self.value
}
pub const fn metadata(&self) -> &Metadata {
&self.metadata
}
pub const fn metadata_mut(&mut self) -> &mut Metadata {
&mut self.metadata
}
pub fn map<U, F: FnOnce(T) -> U>(self, f: F) -> Context<U> {
Context::new(f(self.value), self.metadata)
}
pub fn as_ref(&self) -> Context<&T> {
Context::new(&self.value, self.metadata.clone())
}
pub fn as_mut(&mut self) -> Context<&mut T> {
Context::new(&mut self.value, self.metadata.clone())
}
pub fn as_deref(&self) -> Context<&T::Target>
where
T: core::ops::Deref,
{
Context::new(&*self.value, self.metadata.clone())
}
pub fn as_deref_mut(&mut self) -> Context<&mut T::Target>
where
T: core::ops::DerefMut,
{
Context::new(&mut *self.value, self.metadata.clone())
}
}
impl<T> From<T> for Context<T> {
fn from(value: T) -> Self {
Self::new(value, Metadata::new())
}
}
#[must_use]
pub trait WatcherGuard: 'static {}
impl<T: 'static> WatcherGuard for Option<T> {}
impl<T: WatcherGuard, E: WatcherGuard> WatcherGuard for Result<T, E> {}
impl WatcherGuard for () {}
impl<T1: WatcherGuard, T2: WatcherGuard> WatcherGuard for (T1, T2) {}
#[derive(Debug)]
pub struct OnDrop<F>(Option<F>)
where
F: FnOnce();
impl<F> OnDrop<F>
where
F: FnOnce() + 'static,
{
pub const fn new(f: F) -> Self {
Self(Some(f))
}
#[allow(clippy::needless_pass_by_value)]
pub fn attach(guard: impl WatcherGuard, f: F) -> impl WatcherGuard {
OnDrop::new(move || {
drop(guard);
f();
})
}
}
impl<F> Drop for OnDrop<F>
where
F: FnOnce(),
{
fn drop(&mut self) {
let Some(callback) = self.0.take() else {
panic!("OnDrop::drop called with missing callback");
};
callback();
}
}
pub type BoxWatcherGuard = Box<dyn WatcherGuard>;
impl<T: WatcherGuard + ?Sized> WatcherGuard for Box<T> {}
impl<T: WatcherGuard + ?Sized> WatcherGuard for Rc<T> {}
impl<F: FnOnce() + 'static> WatcherGuard for OnDrop<F> {}
impl Metadata {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn get<T: 'static + Clone>(&self) -> T {
self.try_get()
.unwrap_or_else(|| panic!("Metadata::get missing value for requested type"))
}
#[must_use]
pub fn try_get<T: 'static + Clone>(&self) -> Option<T> {
self.0.try_get()
}
#[must_use]
pub fn with<T: 'static + Clone>(mut self, value: T) -> Self {
self.0.insert(value);
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.0.is_empty()
}
}
pub(crate) type WatcherId = NonZeroUsize;
#[derive(Debug)]
pub struct WatcherManager<T> {
inner: Rc<RefCell<WatcherManagerInner<T>>>,
}
impl<T> Clone for WatcherManager<T> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<T> Default for WatcherManager<T> {
fn default() -> Self {
Self {
inner: Rc::default(),
}
}
}
impl<T: 'static> WatcherManager<T> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_origin(origin: Origin) -> Self {
observe::on_create(origin);
Self {
inner: Rc::new(RefCell::new(WatcherManagerInner::with_origin(origin))),
}
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.borrow().is_empty()
}
pub fn register(&self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
let (id, origin, subscribers) = {
let mut inner = self.inner.borrow_mut();
let id = inner.register(watcher);
(id, inner.origin, inner.len())
};
observe::on_subscribe(origin, subscribers);
id
}
pub fn register_as_guard(
&self,
watcher: impl Fn(Context<T>) + 'static,
) -> WatcherManagerGuard<T> {
let id = self.register(watcher);
let this = self.clone();
WatcherManagerGuard { manager: this, id }
}
pub fn notify(&self, ctx: &Context<T>)
where
T: Clone,
{
let (watchers, origin) = {
let inner = self.inner.borrow();
(inner.watchers_snapshot(), inner.origin)
};
if watchers.is_empty() {
return;
}
observe::on_notify(origin, watchers.len());
for watcher in watchers {
watcher(ctx.clone());
}
}
pub fn cancel(&self, id: WatcherId) {
let (removed, origin, subscribers) = {
let mut inner = self.inner.borrow_mut();
let removed = inner.cancel(id);
(removed, inner.origin, inner.len())
};
observe::on_unsubscribe(origin, subscribers);
drop(removed);
}
}
#[must_use]
#[derive(Debug)]
pub struct WatcherManagerGuard<T: 'static> {
manager: WatcherManager<T>,
id: WatcherId,
}
impl<T> WatcherGuard for WatcherManagerGuard<T> {}
impl<T: 'static> Drop for WatcherManagerGuard<T> {
fn drop(&mut self) {
self.manager.cancel(self.id);
}
}
struct WatcherManagerInner<T> {
id: WatcherId,
map: BTreeMap<WatcherId, Watcher<T>>,
origin: Origin,
}
impl<T> Debug for WatcherManagerInner<T> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(type_name::<Self>())
}
}
impl<T> Default for WatcherManagerInner<T> {
fn default() -> Self {
Self {
id: WatcherId::MIN,
map: BTreeMap::new(),
origin: Origin::unattributed(),
}
}
}
impl<T> Drop for WatcherManagerInner<T> {
fn drop(&mut self) {
observe::on_drop(self.origin);
}
}
impl<T: 'static> WatcherManagerInner<T> {
fn with_origin(origin: Origin) -> Self {
Self {
id: WatcherId::MIN,
map: BTreeMap::new(),
origin,
}
}
pub fn is_empty(&self) -> bool {
self.map.is_empty()
}
fn len(&self) -> usize {
self.map.len()
}
const fn assign(&mut self) -> WatcherId {
let id = self.id;
self.id = match self.id.checked_add(1) {
Some(id) => id,
None => panic!("`id` grows beyond `usize::MAX`"),
};
id
}
pub fn register(&mut self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
let id = self.assign();
self.map.insert(id, Rc::new(watcher));
id
}
fn watchers_snapshot(&self) -> Vec<Watcher<T>> {
self.map.values().cloned().collect()
}
pub fn cancel(&mut self, id: WatcherId) -> Option<Watcher<T>> {
self.map.remove(&id)
}
}
#[cfg(test)]
mod tests {
use alloc::rc::Rc;
use core::cell::Cell;
use super::{Context, OnDrop, WatcherGuard, WatcherManager};
#[test]
fn cancel_drops_removed_watcher_after_releasing_borrow() {
let manager = WatcherManager::<i32>::new();
let nested = manager.register_as_guard(|_| ());
let owner = manager.register(move |_: Context<i32>| {
let _owns_nested_guard = &nested;
});
manager.cancel(owner);
assert!(manager.is_empty());
}
#[test]
fn attach_holds_the_guard_until_the_result_drops() {
struct Probe(Rc<Cell<bool>>);
impl WatcherGuard for Probe {}
impl Drop for Probe {
fn drop(&mut self) {
self.0.set(true);
}
}
let dropped = Rc::new(Cell::new(false));
let attached = OnDrop::attach(Probe(Rc::clone(&dropped)), || ());
assert!(!dropped.get(), "attach dropped the guard early");
drop(attached);
assert!(dropped.get());
}
}