zwire 0.4.0

Zero-dependency, no_std-compatible transactional reactive state engine: scoped push-pull arena, rebaseable optimistic layers + STM drafts, exact incremental Top-K collections, and open @zwire/core wire protocols
Documentation
//! Fine-grained reactive key-value stores and mutable-draft projections (`#![no_std]`).
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use core::cell::RefCell;
use core::fmt;

use zwire_core::{Atom, Computed, EvalContext, HookGuard, Scope, Signal};

struct MapStoreInner<K: Ord + 'static, V: 'static> {
    values: BTreeMap<K, V>,
    fields: BTreeMap<K, (Atom<Option<V>>, HookGuard)>,
}

/// Fine-grained reactive key-value map backed by lazy per-key [`Atom<Option<V>>`] handles.
///
/// Field atoms are allocated on demand by [`Self::field`] and automatically pruned from the
/// internal map (and disposed in the [`Scope`]) via `on_unwatched` once their last subscriber
/// detaches.
pub struct MapStore<K: Ord + Clone + 'static, V: Clone + PartialEq + 'static> {
    scope: Scope,
    len_atom: Atom<usize>,
    inner: Rc<RefCell<MapStoreInner<K, V>>>,
}

impl<K: Ord + Clone + 'static, V: Clone + PartialEq + 'static> Clone for MapStore<K, V> {
    fn clone(&self) -> Self {
        Self {
            scope: self.scope.clone(),
            len_atom: self.len_atom,
            inner: Rc::clone(&self.inner),
        }
    }
}

impl<K: Ord + Clone + fmt::Debug + 'static, V: Clone + PartialEq + fmt::Debug + 'static> fmt::Debug
    for MapStore<K, V>
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut s = f.debug_struct("MapStore");
        if let Ok(inner) = self.inner.try_borrow() {
            s.field("len", &inner.values.len())
                .field("live_fields", &inner.fields.len())
                .finish_non_exhaustive()
        } else {
            s.field("state", &"<borrowed>").finish_non_exhaustive()
        }
    }
}

impl<K: Ord + Clone + 'static, V: Clone + PartialEq + 'static> MapStore<K, V> {
    /// Creates an empty [`MapStore`] bound to `scope`.
    pub fn new(scope: &Scope) -> Self {
        Self {
            scope: scope.clone(),
            len_atom: scope.atom(0usize),
            inner: Rc::new(RefCell::new(MapStoreInner {
                values: BTreeMap::new(),
                fields: BTreeMap::new(),
            })),
        }
    }

    /// Creates a [`MapStore`] pre-populated with entries from `iter`.
    pub fn from_entries(scope: &Scope, iter: impl IntoIterator<Item = (K, V)>) -> Self {
        let values: BTreeMap<K, V> = iter.into_iter().collect();
        let len = values.len();
        Self {
            scope: scope.clone(),
            len_atom: scope.atom(len),
            inner: Rc::new(RefCell::new(MapStoreInner {
                values,
                fields: BTreeMap::new(),
            })),
        }
    }

    /// Returns a lazy per-key [`Atom<Option<V>>`] that automatically prunes and disposes itself
    /// when its subscriber count transitions `1 -> 0`.
    pub fn field(&self, key: K) -> Atom<Option<V>> {
        if let Some((atom, _)) = self.inner.borrow().fields.get(&key) {
            return *atom;
        }
        let initial = self.inner.borrow().values.get(&key).cloned();
        let atom = self.scope.atom(initial);
        let weak_inner = Rc::downgrade(&self.inner);
        let weak_scope = self.scope.downgrade();
        let prune_key = key.clone();
        let guard = self.scope.on_unwatched(atom, move || {
            let Some(rc_inner) = weak_inner.upgrade() else {
                return;
            };
            let removed = {
                let mut inner = rc_inner.borrow_mut();
                if inner
                    .fields
                    .get(&prune_key)
                    .is_some_and(|(stored, _)| *stored == atom)
                {
                    inner.fields.remove(&prune_key)
                } else {
                    None
                }
            };
            if let Some((pruned_atom, pruned_guard)) = removed {
                drop(pruned_guard);
                if let Some(sc) = weak_scope.upgrade() {
                    let _ = sc.dispose(pruned_atom);
                }
            }
        });

        let mut inner = self.inner.borrow_mut();
        if let Some((existing, _)) = inner.fields.get(&key) {
            let existing = *existing;
            drop(inner);
            drop(guard);
            let _ = self.scope.dispose(atom);
            return existing;
        }
        inner.fields.insert(key, (atom, guard));
        atom
    }

    /// Reads and clones the current value associated with `key`, if present.
    pub fn get(&self, key: &K) -> Option<V> {
        self.inner.borrow().values.get(key).cloned()
    }

    /// Inserts or updates `key` with `value`, notifying only subscribers of `key` and length.
    pub fn set_key(&self, key: K, value: V) {
        let (field_atom, new_len) = {
            let mut inner = self.inner.borrow_mut();
            let atom = inner.fields.get(&key).map(|(a, _)| *a);
            inner.values.insert(key, value.clone());
            (atom, inner.values.len())
        };
        self.scope.batch(|| {
            if let Some(atom) = field_atom {
                self.scope.set(atom, Some(value));
            }
            self.scope.set(self.len_atom, new_len);
        });
    }

    /// Removes `key` from the map, returning its previous value if present and notifying any
    /// subscribers watching that key or the map length.
    pub fn delete_key(&self, key: &K) -> Option<V> {
        let (removed, field_atom, new_len) = {
            let mut inner = self.inner.borrow_mut();
            let removed = inner.values.remove(key);
            let atom = inner.fields.get(key).map(|(a, _)| *a);
            (removed, atom, inner.values.len())
        };
        if removed.is_some() {
            self.scope.batch(|| {
                if let Some(atom) = field_atom {
                    self.scope.set(atom, None);
                }
                self.scope.set(self.len_atom, new_len);
            });
        }
        removed
    }

    /// Returns a cloned [`BTreeMap`] snapshot of all current key-value pairs.
    pub fn snapshot(&self) -> BTreeMap<K, V> {
        self.inner.borrow().values.clone()
    }

    /// Returns the number of entries currently stored in the map.
    pub fn len(&self) -> usize {
        self.inner.borrow().values.len()
    }

    /// Returns `true` if the map contains no entries.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a reactive [`Signal<usize>`] tracking the number of entries in the map.
    pub const fn len_signal(&self) -> Signal<usize> {
        self.len_atom.as_signal()
    }

    /// Returns the number of currently allocated per-key field atoms (useful for diagnostics).
    pub fn live_field_count(&self) -> usize {
        self.inner.borrow().fields.len()
    }
}

/// Creates an incremental derived [`Computed<T>`] backed by a mutable draft `&mut T`.
///
/// `f` mutates the draft in place and returns `true` when downstream subscribers should be
/// notified, or `false` to suppress propagation without requiring `T: PartialEq`.
pub fn projection<T: Clone + 'static>(
    scope: &Scope,
    initial: T,
    f: impl Fn(&EvalContext<'_>, &mut T) -> bool + 'static,
) -> Computed<T> {
    scope.projection(initial, f)
}