use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::{Cell, RefCell};
use zwire_collections::{AcceptAll, ItemFilter, KeyedCollection, TopKViewId};
use zwire_core::internal::{
alloc_token, batch_depth, create_external_signal, emit_external, is_node_alive,
propagate_external, remove_flush_hook, schedule_flush_hook, update_external_silent,
};
use zwire_core::{CleanupFn, Computed, NodeId, Scope};
struct WatchedTopK {
view_id: TopKViewId,
signal_id: NodeId,
watched: Rc<Cell<bool>>,
dirty_notified: Rc<Cell<bool>>,
}
pub struct PureReactiveCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
Flt: ItemFilter<T> + 'static,
{
scope: Scope,
inner: Rc<RefCell<KeyedCollection<T, K, S, IdFn, SkFn, Flt>>>,
views: Rc<RefCell<Vec<WatchedTopK>>>,
cached_top_k: RefCell<BTreeMap<usize, Computed<Vec<T>>>>,
flush_token: u64,
flush_scheduled: Rc<Cell<bool>>,
}
impl<T, K, S, IdFn, SkFn, Flt> core::fmt::Debug for PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
Flt: ItemFilter<T> + 'static,
{
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
let mut s = f.debug_struct("PureReactiveCollection");
if let Ok(inner) = self.inner.try_borrow() {
s.field("len", &inner.len())
.field("indexed_len", &inner.indexed_len())
.field("version", &inner.version());
} else {
s.field("state", &"<borrowed>");
}
s.field("flush_scheduled", &self.flush_scheduled.get())
.finish_non_exhaustive()
}
}
impl<T, K, S, IdFn, SkFn> PureReactiveCollection<T, K, S, IdFn, SkFn, AcceptAll>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
{
pub fn new(scope: &Scope, get_id: IdFn, sort_key: SkFn) -> Self {
Self::from_parts(scope, get_id, sort_key, AcceptAll)
}
}
impl<T, K, S, IdFn, SkFn, Flt> PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
Flt: Fn(&T) -> bool + 'static,
{
pub fn with_filter(scope: &Scope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
Self::from_parts(scope, get_id, sort_key, filter)
}
}
impl<T, K, S, IdFn, SkFn, Flt> PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
Flt: ItemFilter<T> + 'static,
{
pub fn from_parts(scope: &Scope, get_id: IdFn, sort_key: SkFn, filter: Flt) -> Self {
let flush_token = alloc_token(scope);
Self {
scope: scope.clone(),
inner: Rc::new(RefCell::new(KeyedCollection::from_parts(
get_id, sort_key, filter,
))),
views: Rc::new(RefCell::new(Vec::new())),
cached_top_k: RefCell::new(BTreeMap::new()),
flush_token,
flush_scheduled: Rc::new(Cell::new(false)),
}
}
#[inline]
pub fn len(&self) -> usize {
self.inner.borrow().len()
}
#[inline]
pub fn is_empty(&self) -> bool {
self.inner.borrow().is_empty()
}
#[inline]
pub fn indexed_len(&self) -> usize {
self.inner.borrow().indexed_len()
}
#[inline]
pub fn get(&self, id: &K) -> Option<T> {
self.inner.borrow().get(id).cloned()
}
#[inline]
pub fn contains_key(&self, id: &K) -> bool {
self.inner.borrow().contains_key(id)
}
#[inline]
pub fn get_top_k(&self, k: usize) -> Vec<T> {
self.inner.borrow().top_k(k)
}
pub fn upsert(&self, item: T) {
self.inner.borrow_mut().upsert(item);
self.notify_top_k();
}
pub fn upsert_many<I>(&self, items: I)
where
I: IntoIterator<Item = T>,
{
self.inner.borrow_mut().upsert_many(items);
self.notify_top_k();
}
pub fn delete(&self, id: &K) -> Option<T> {
let removed = self.inner.borrow_mut().delete(id)?;
self.notify_top_k();
Some(removed)
}
pub fn clear(&self) {
let changed = {
let mut col = self.inner.borrow_mut();
if col.is_empty() {
false
} else {
col.clear();
true
}
};
if changed {
self.notify_top_k();
}
}
pub fn top_k_signal(&self, k: usize) -> Computed<Vec<T>> {
self.prune_disposed_views();
if let Some(&sig) = self.cached_top_k.borrow().get(&k)
&& is_node_alive(&self.scope, sig.id())
{
return sig;
}
let (view_id, initial) = {
let mut col = self.inner.borrow_mut();
let view_id = col.watch_top_k(k);
let initial = col.view_mapped(view_id, T::clone);
(view_id, initial)
};
let sig = self.build_top_k_signal(view_id, initial);
self.cached_top_k.borrow_mut().insert(k, sig);
sig
}
pub fn dispose_top_k_signal(&self, sig: Computed<Vec<T>>) -> bool {
let target = sig.id();
self.cached_top_k
.borrow_mut()
.retain(|_, cached| cached.id() != target);
let removed_view = {
let mut views = self.views.borrow_mut();
views
.iter()
.position(|v| v.signal_id == target)
.map(|idx| views.swap_remove(idx).view_id)
};
if let Some(view_id) = removed_view {
self.inner.borrow_mut().unwatch_top_k(view_id);
}
let disposed = self.scope.dispose(sig);
removed_view.is_some() || disposed
}
fn prune_disposed_views(&self) {
let dead: Vec<TopKViewId> = {
let mut views = self.views.borrow_mut();
views
.extract_if(.., |v| !is_node_alive(&self.scope, v.signal_id))
.map(|v| v.view_id)
.collect()
};
if !dead.is_empty() {
let mut col = self.inner.borrow_mut();
for vid in dead {
col.unwatch_top_k(vid);
}
self.cached_top_k
.borrow_mut()
.retain(|_, sig| is_node_alive(&self.scope, sig.id()));
}
}
fn build_top_k_signal(&self, view_id: TopKViewId, initial: Vec<T>) -> Computed<Vec<T>> {
let watched = Rc::new(Cell::new(false));
let dirty_notified = Rc::new(Cell::new(false));
let signal_id_cell: Rc<Cell<Option<NodeId>>> = Rc::new(Cell::new(None));
let poll_inner = Rc::clone(&self.inner);
let poll_id = Rc::clone(&signal_id_cell);
let poll_dirty = Rc::clone(&dirty_notified);
let poll = Rc::new(move |sc: &Scope| {
let Some(sid) = poll_id.get() else {
return;
};
let maybe_next = {
let mut col = poll_inner.borrow_mut();
col.sync_view(view_id)
.then(|| col.view_mapped(view_id, T::clone))
};
poll_dirty.set(false);
if let Some(next) = maybe_next {
update_external_silent(sc, sid, next);
}
});
let watch_inner = Rc::clone(&self.inner);
let watch_flag = Rc::clone(&watched);
let watch_dirty = Rc::clone(&dirty_notified);
let watch_id = Rc::clone(&signal_id_cell);
let weak_sc = self.scope.downgrade();
let on_watched = Rc::new(move || -> Option<CleanupFn> {
watch_flag.set(true);
if let (Some(sid), Some(sc_watch)) = (watch_id.get(), weak_sc.upgrade()) {
let maybe_next = {
let mut col = watch_inner.borrow_mut();
col.sync_view(view_id)
.then(|| col.view_mapped(view_id, T::clone))
};
watch_dirty.set(false);
if let Some(next) = maybe_next {
update_external_silent(&sc_watch, sid, next);
}
}
let unw = Rc::clone(&watch_flag);
let unw_dirty = Rc::clone(&watch_dirty);
Some(Box::new(move || {
unw.set(false);
unw_dirty.set(false);
}))
});
let eq: Rc<dyn Fn(&Vec<T>, &Vec<T>) -> bool> = Rc::new(|a, b| a == b);
let sig =
create_external_signal(&self.scope, initial, Some(eq), poll, Some(on_watched), None);
signal_id_cell.set(Some(sig.id()));
self.views.borrow_mut().push(WatchedTopK {
view_id,
signal_id: sig.id(),
watched,
dirty_notified,
});
sig
}
fn notify_top_k(&self) {
let mut first: Option<(TopKViewId, NodeId)> = None;
let mut rest: Vec<(TopKViewId, NodeId)> = Vec::new();
{
let views = self.views.borrow();
if views.is_empty() {
return;
}
let col = self.inner.borrow();
for v in views.iter() {
if v.watched.get() && col.is_view_dirty(v.view_id) {
let pair = (v.view_id, v.signal_id);
if first.is_none() {
first = Some(pair);
} else {
rest.push(pair);
}
}
}
}
let Some((first_vid, first_sid)) = first else {
return;
};
if batch_depth(&self.scope) == 0 {
if rest.is_empty() {
let maybe_next = {
let mut col = self.inner.borrow_mut();
col.sync_view(first_vid)
.then(|| col.view_mapped(first_vid, T::clone))
};
if let Some(next) = maybe_next {
emit_external(&self.scope, first_sid, next);
}
return;
}
let mut updates = Vec::with_capacity(1 + rest.len());
{
let mut col = self.inner.borrow_mut();
if col.sync_view(first_vid) {
updates.push((first_sid, col.view_mapped(first_vid, T::clone)));
}
for (vid, sid) in rest {
if col.sync_view(vid) {
updates.push((sid, col.view_mapped(vid, T::clone)));
}
}
}
if updates.len() == 1 {
let (sid, next) = updates.into_iter().next().expect("len == 1");
emit_external(&self.scope, sid, next);
} else if !updates.is_empty() {
self.scope.batch(|| {
for (sid, next) in updates {
emit_external(&self.scope, sid, next);
}
});
}
return;
}
let mut to_propagate: Vec<NodeId> = Vec::new();
{
let col = self.inner.borrow();
let views = self.views.borrow();
for v in views.iter() {
if v.watched.get() && !v.dirty_notified.get() && col.is_view_dirty(v.view_id) {
v.dirty_notified.set(true);
to_propagate.push(v.signal_id);
}
}
}
for sid in to_propagate {
propagate_external(&self.scope, sid);
}
if !self.flush_scheduled.get() {
self.flush_scheduled.set(true);
let inner = Rc::clone(&self.inner);
let views = Rc::clone(&self.views);
let scheduled = Rc::clone(&self.flush_scheduled);
let weak_sc = self.scope.downgrade();
schedule_flush_hook(
&self.scope,
self.flush_token,
Rc::new(move || {
scheduled.set(false);
let Some(sc) = weak_sc.upgrade() else {
return;
};
let watched: Vec<_> = {
let views = views.borrow();
views
.iter()
.filter_map(|v| {
v.dirty_notified.set(false);
v.watched.get().then_some((v.signal_id, v.view_id))
})
.collect()
};
let mut updates = Vec::new();
{
let mut col = inner.borrow_mut();
for (sid, vid) in watched {
if col.sync_view(vid) {
updates.push((sid, col.view_mapped(vid, T::clone)));
}
}
}
for (sid, next) in updates {
emit_external(&sc, sid, next);
}
}),
);
}
}
}
impl<T, K, S, IdFn, SkFn, Flt> Drop for PureReactiveCollection<T, K, S, IdFn, SkFn, Flt>
where
T: Clone + PartialEq + 'static,
K: Ord + Clone + 'static,
S: Ord + Copy + 'static,
IdFn: Fn(&T) -> K + 'static,
SkFn: Fn(&T) -> S + 'static,
Flt: ItemFilter<T> + 'static,
{
fn drop(&mut self) {
remove_flush_hook(&self.scope, self.flush_token);
}
}
#[cfg(test)]
mod tests {
use super::PureReactiveCollection;
use crate::ReactiveCollection;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cell::Cell;
use core::cmp::Reverse;
use zwire_core::Scope;
#[derive(Debug, Clone, PartialEq, Eq)]
struct Row {
id: u32,
score: i32,
active: bool,
}
#[test]
fn pure_reactive_collection_matches_reactive_collection_top_50_over_1000_random_ops() {
let scope = Scope::new();
let rc = ReactiveCollection::with_filter(
&scope,
|r: &Row| r.id,
|a, b| b.score.cmp(&a.score),
|r| r.active && r.score >= 700,
);
let pure = PureReactiveCollection::with_filter(
&scope,
|r: &Row| r.id,
|r: &Row| Reverse(r.score),
|r| r.active && r.score >= 700,
);
let mut seed = 0xDEAD_BEEFu32;
let mut next_u32 = || {
seed ^= seed << 13;
seed ^= seed >> 17;
seed ^= seed << 5;
seed
};
let initial_rows: Vec<Row> = (0..300u32)
.map(|id| {
let r = next_u32();
Row {
id,
score: i32::try_from(r % 1_000).unwrap_or(0),
active: (r & 1) == 0,
}
})
.collect();
rc.upsert_many(initial_rows.clone());
pure.upsert_many(initial_rows);
let rc_top50 = rc.top_k_signal(50);
let pure_top50 = pure.top_k_signal(50);
let rc_notifs = Rc::new(Cell::new(0usize));
let pure_notifs = Rc::new(Cell::new(0usize));
let rc_n = Rc::clone(&rc_notifs);
let pure_n = Rc::clone(&pure_notifs);
let _sub_rc = scope.subscribe(rc_top50, move |_| rc_n.set(rc_n.get() + 1));
let _sub_pure = scope.subscribe(pure_top50, move |_| pure_n.set(pure_n.get() + 1));
assert_eq!(scope.get(rc_top50), scope.get(pure_top50));
assert_eq!(rc.len(), pure.len());
for step in 0..1_000u32 {
let op = next_u32() % 5;
let id = next_u32() % 400;
if op == 0 {
let removed_rc = rc.delete(&id);
let removed_pure = pure.delete(&id);
assert_eq!(removed_rc, removed_pure, "delete mismatch at step {step}");
} else {
let score = i32::try_from(next_u32() % 1_000).unwrap_or(0);
let active = (next_u32() & 1) == 0;
let row = Row { id, score, active };
rc.upsert(row.clone());
pure.upsert(row);
}
assert_eq!(rc.len(), pure.len(), "len mismatch at step {step}");
assert_eq!(
rc.get(&id),
pure.get(&id),
"get mismatch for id {id} at step {step}"
);
assert_eq!(
scope.get(rc_top50),
scope.get(pure_top50),
"top_k(50) signal mismatch at step {step}"
);
}
assert_eq!(rc_notifs.get(), pure_notifs.get());
assert!(pure_notifs.get() > 0);
assert!(pure_notifs.get() < 1_000);
}
#[test]
fn pure_reactive_collection_batching_and_dispose() {
let scope = Scope::new();
let pure = PureReactiveCollection::new(&scope, |r: &Row| r.id, |r: &Row| Reverse(r.score));
let top2 = pure.top_k_signal(2);
let hits = Rc::new(Cell::new(0usize));
let h = Rc::clone(&hits);
let _sub = scope.subscribe(top2, move |_| h.set(h.get() + 1));
scope.batch(|| {
pure.upsert(Row {
id: 1,
score: 10,
active: true,
});
pure.upsert(Row {
id: 2,
score: 50,
active: true,
});
pure.upsert(Row {
id: 3,
score: 30,
active: true,
});
});
assert_eq!(hits.get(), 1);
assert_eq!(
scope
.get(top2)
.into_iter()
.map(|r| r.id)
.collect::<Vec<_>>(),
alloc::vec![2, 3]
);
assert!(pure.dispose_top_k_signal(top2));
}
}