use alloc::{boxed::Box, collections::VecDeque, 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<[(TypeId, Rc<dyn Any>)]>);
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 fn into_parts(self) -> (T, Metadata) {
(self.value, self.metadata)
}
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> {
let id = TypeId::of::<T>();
self.0
.iter()
.find(|(key, _)| *key == id)
.and_then(|(_, value)| value.downcast_ref::<T>())
.cloned()
}
#[must_use]
pub fn with<T: 'static + Clone>(self, value: T) -> Self {
self.with_erased(TypeId::of::<T>(), Rc::new(value))
}
#[must_use]
pub fn merge(self, other: Self) -> Self {
if self.is_empty() {
return other;
}
other
.0
.into_iter()
.fold(self, |merged, (id, value)| merged.with_erased(id, value))
}
fn with_erased(mut self, id: TypeId, value: Rc<dyn Any>) -> Self {
if let Some(slot) = self.0.iter_mut().find(|(key, _)| *key == id) {
slot.1 = value;
return self;
}
let mut entries = Vec::from(self.0);
entries.push((id, value));
self.0 = entries.into_boxed_slice();
self
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
pub type WatcherId = NonZeroUsize;
type Entries<W> = Rc<Vec<(WatcherId, Rc<W>)>>;
pub struct WatcherRegistry<W: ?Sized> {
inner: Rc<RefCell<RegistryInner<W>>>,
}
impl<W: ?Sized> Debug for WatcherRegistry<W> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(type_name::<Self>())
}
}
impl<W: ?Sized> Clone for WatcherRegistry<W> {
fn clone(&self) -> Self {
Self {
inner: self.inner.clone(),
}
}
}
impl<W: ?Sized> Default for WatcherRegistry<W> {
fn default() -> Self {
Self::with_origin_unobserved(Origin::unattributed())
}
}
impl<W: ?Sized + 'static> WatcherRegistry<W> {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_origin(origin: Origin) -> Self {
observe::on_create(origin);
Self::with_origin_unobserved(origin)
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.inner.borrow().entries.is_empty()
}
#[must_use]
pub fn len(&self) -> usize {
self.inner.borrow().entries.len()
}
pub fn insert(&self, watcher: Rc<W>) -> WatcherId {
let (id, origin, subscribers) = {
let mut inner = self.inner.borrow_mut();
let id = inner.assign();
Rc::make_mut(&mut inner.entries).push((id, watcher));
(id, inner.origin, inner.entries.len())
};
observe::on_subscribe(origin, subscribers);
id
}
pub fn insert_as_guard(&self, watcher: Rc<W>) -> RegistryGuard<W> {
let id = self.insert(watcher);
RegistryGuard {
registry: self.clone(),
id,
}
}
pub fn cancel(&self, id: WatcherId) {
let (removed, origin, subscribers) = {
let mut inner = self.inner.borrow_mut();
let removed = match inner.entries.binary_search_by_key(&id, |(id, _)| *id) {
Ok(position) => Some(Rc::make_mut(&mut inner.entries).remove(position)),
Err(_) => None,
};
(removed, inner.origin, inner.entries.len())
};
observe::on_unsubscribe(origin, subscribers);
drop(removed);
}
pub fn notify_with<A: Clone + 'static>(&self, value: A, mut call: impl FnMut(&W, A) + 'static) {
let (entries, origin) = {
let mut inner = self.inner.borrow_mut();
let entries = Rc::clone(&inner.entries);
let origin = inner.origin;
if let Some(queue) = &mut inner.queue {
queue.push_back((
entries,
Box::new(move |watcher| call(watcher, value.clone())),
));
return;
}
inner.queue = Some(VecDeque::new());
(entries, origin)
};
let _scope = DeliveryScope(&self.inner);
let Some(((_, last), rest)) = entries.split_last() else {
return;
};
observe::on_notify(origin, entries.len());
for (_, watcher) in rest {
call(watcher, value.clone());
}
call(last, value);
loop {
let queued = {
let mut inner = self.inner.borrow_mut();
let Some(queue) = inner.queue.as_mut() else {
break;
};
queue.pop_front()
};
let Some((raised, mut delivery)) = queued else {
break;
};
let (current, origin) = {
let inner = self.inner.borrow();
(Rc::clone(&inner.entries), inner.origin)
};
let still_registered =
|id: &WatcherId| current.binary_search_by_key(id, |(id, _)| *id).is_ok();
let recipients = raised.iter().filter(|(id, _)| still_registered(id)).count();
if recipients == 0 {
continue;
}
observe::on_notify(origin, recipients);
for (_, watcher) in raised.iter().filter(|(id, _)| still_registered(id)) {
delivery(watcher);
}
}
}
}
impl<W: ?Sized> WatcherRegistry<W> {
fn with_origin_unobserved(origin: Origin) -> Self {
Self {
inner: Rc::new(RefCell::new(RegistryInner {
next: WatcherId::MIN,
entries: Rc::new(Vec::new()),
origin,
queue: None,
})),
}
}
}
#[must_use]
pub struct RegistryGuard<W: ?Sized + 'static> {
registry: WatcherRegistry<W>,
id: WatcherId,
}
impl<W: ?Sized> Debug for RegistryGuard<W> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("RegistryGuard")
.field("registry", &self.registry)
.field("id", &self.id)
.finish()
}
}
impl<W: ?Sized + 'static> WatcherGuard for RegistryGuard<W> {}
impl<W: ?Sized + 'static> Drop for RegistryGuard<W> {
fn drop(&mut self) {
self.registry.cancel(self.id);
}
}
pub type WatcherManager<T> = WatcherRegistry<dyn Fn(Context<T>)>;
pub type WatcherManagerGuard<T> = RegistryGuard<dyn Fn(Context<T>)>;
impl<T: 'static> WatcherRegistry<dyn Fn(Context<T>)> {
pub fn register(&self, watcher: impl Fn(Context<T>) + 'static) -> WatcherId {
self.insert(Rc::new(watcher))
}
pub fn register_as_guard(
&self,
watcher: impl Fn(Context<T>) + 'static,
) -> WatcherManagerGuard<T> {
self.insert_as_guard(Rc::new(watcher))
}
pub fn notify(&self, ctx: &Context<T>)
where
T: Clone,
{
if self.is_empty() {
return;
}
self.notify_owned(ctx.clone());
}
pub fn notify_owned(&self, ctx: Context<T>)
where
T: Clone,
{
self.notify_with(ctx, |watcher, ctx| watcher(ctx));
}
}
type QueuedDelivery<W> = Box<dyn FnMut(&W)>;
struct RegistryInner<W: ?Sized> {
next: WatcherId,
entries: Entries<W>,
origin: Origin,
queue: Option<VecDeque<(Entries<W>, QueuedDelivery<W>)>>,
}
struct DeliveryScope<'a, W: ?Sized>(&'a RefCell<RegistryInner<W>>);
impl<W: ?Sized> Drop for DeliveryScope<'_, W> {
fn drop(&mut self) {
let queue = self.0.borrow_mut().queue.take();
drop(queue);
}
}
impl<W: ?Sized> Drop for RegistryInner<W> {
fn drop(&mut self) {
observe::on_drop(self.origin);
}
}
impl<W: ?Sized> RegistryInner<W> {
const fn assign(&mut self) -> WatcherId {
let id = self.next;
self.next = match self.next.checked_add(1) {
Some(id) => id,
None => panic!("`id` grows beyond `usize::MAX`"),
};
id
}
}
#[cfg(test)]
mod tests {
use alloc::{rc::Rc, vec, vec::Vec};
use core::cell::{Cell, RefCell};
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());
}
#[test]
fn reentrant_notify_is_queued_until_the_round_finishes() {
let manager = WatcherManager::<i32>::new();
let seen_first = Rc::new(RefCell::new(Vec::new()));
let seen_second = Rc::new(RefCell::new(Vec::new()));
let fired = Rc::new(Cell::new(false));
manager.register({
let manager = manager.clone();
let seen = Rc::clone(&seen_first);
let fired = Rc::clone(&fired);
move |context: Context<i32>| {
let value = context.into_value();
seen.borrow_mut().push(value);
if value == 1 && !fired.replace(true) {
manager.notify_owned(Context::from(2));
}
}
});
manager.register({
let seen = Rc::clone(&seen_second);
move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
});
manager.notify_owned(Context::from(1));
assert_eq!(*seen_first.borrow(), vec![1, 2]);
assert_eq!(*seen_second.borrow(), vec![1, 2]);
}
#[test]
fn a_watcher_registered_mid_round_misses_queued_deliveries() {
let manager = WatcherManager::<i32>::new();
let seen_late = Rc::new(RefCell::new(Vec::new()));
let done = Rc::new(Cell::new(false));
manager.register({
let manager = manager.clone();
let seen_late = Rc::clone(&seen_late);
let done = Rc::clone(&done);
move |_context: Context<i32>| {
if done.replace(true) {
return;
}
manager.notify_owned(Context::from(2));
manager.register({
let seen_late = Rc::clone(&seen_late);
move |context: Context<i32>| {
seen_late.borrow_mut().push(context.into_value());
}
});
}
});
manager.notify_owned(Context::from(1));
assert!(
seen_late.borrow().is_empty(),
"the late watcher must miss the delivery raised before it registered"
);
manager.notify_owned(Context::from(3));
assert_eq!(
*seen_late.borrow(),
vec![3],
"the late watcher takes effect from the next notification"
);
}
#[test]
fn a_watcher_cancelled_mid_round_misses_queued_deliveries() {
let manager = WatcherManager::<i32>::new();
let done = Rc::new(Cell::new(false));
let cancelled_id = Rc::new(RefCell::new(None));
let seen_cancelled = Rc::new(RefCell::new(Vec::new()));
let seen_later = Rc::new(RefCell::new(Vec::new()));
manager.register({
let manager = manager.clone();
let done = Rc::clone(&done);
let cancelled_id = Rc::clone(&cancelled_id);
move |context: Context<i32>| {
if *context.value() == 1 && !done.replace(true) {
manager.notify_owned(Context::from(2));
if let Some(id) = cancelled_id.borrow_mut().take() {
manager.cancel(id);
}
}
}
});
let second = manager.register({
let seen = Rc::clone(&seen_cancelled);
move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
});
*cancelled_id.borrow_mut() = Some(second);
manager.register({
let seen = Rc::clone(&seen_later);
move |context: Context<i32>| seen.borrow_mut().push(context.into_value())
});
manager.notify_owned(Context::from(1));
assert_eq!(
*seen_cancelled.borrow(),
vec![1],
"round 1's snapshot still reached it; the queued delivery did not"
);
assert_eq!(*seen_later.borrow(), vec![1, 2]);
}
}