zwire 0.2.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
use alloc::collections::BTreeMap;
use alloc::rc::Rc;
use alloc::vec::Vec;
use core::cmp::Ordering;
use core::fmt;

use zwire_core::{Atom, Computed, Scope};
use zwire_tx::OptimisticLayer;

/// A detached edit of a keyed collection. Updating an item's key replaces any displaced row.
pub struct RowEdit<'a, T, K> {
    rows: &'a mut BTreeMap<K, T>,
    get_id: &'a dyn Fn(&T) -> K,
}

impl<T, K> fmt::Debug for RowEdit<'_, T, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("RowEdit")
            .field("len", &self.rows.len())
            .finish_non_exhaustive()
    }
}

impl<T, K: Ord> RowEdit<'_, T, K> {
    /// Borrows a row within this edit.
    pub fn get(&self, id: &K) -> Option<&T> {
        self.rows.get(id)
    }

    /// Inserts or replaces a row.
    pub fn upsert(&mut self, item: T) {
        self.rows.insert((self.get_id)(&item), item);
    }

    /// Updates the row, returning false when it was absent at replay time.
    pub fn update(&mut self, id: &K, change: impl FnOnce(&T) -> T) -> bool {
        let Some(prev) = self.rows.get(id) else {
            return false;
        };
        let next = change(prev);
        self.rows.remove(id);
        self.upsert(next);
        true
    }

    /// Removes a row and returns its previous value.
    pub fn delete(&mut self, id: &K) -> Option<T> {
        self.rows.remove(id)
    }
}

/// Copy-on-write collection snapshots for draft isolation and replayable optimistic edits.
///
/// Normal edits rebase existing intents. A draft intercepts edits made inside
/// `Draft::run`. Each edit copies the row map once, independently of the number of row changes.
pub struct TransactionalCollection<T: 'static, K: 'static> {
    scope: Scope,
    rows: Atom<BTreeMap<K, T>>,
    sorted: Computed<Vec<T>>,
    get_id: Rc<dyn Fn(&T) -> K>,
}

impl<T, K> fmt::Debug for TransactionalCollection<T, K> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("TransactionalCollection")
            .field("rows", &self.rows.id())
            .field("sorted", &self.sorted.id())
            .finish_non_exhaustive()
    }
}

impl<T: Clone + PartialEq + 'static, K: Clone + Ord + 'static> TransactionalCollection<T, K> {
    /// Creates an empty collection indexed by comparator then key.
    pub fn new(
        scope: &Scope,
        get_id: impl Fn(&T) -> K + 'static,
        compare: impl Fn(&T, &T) -> Ordering + 'static,
    ) -> Self {
        Self::with_filter(scope, get_id, compare, |_| true)
    }

    /// Creates an empty collection tracking a filtered, sorted index.
    pub fn with_filter(
        scope: &Scope,
        get_id: impl Fn(&T) -> K + 'static,
        compare: impl Fn(&T, &T) -> Ordering + 'static,
        filter: impl Fn(&T) -> bool + 'static,
    ) -> Self {
        let rows = scope.atom(BTreeMap::<K, T>::new());
        let sorted = scope.computed(move |cx| {
            cx.with(rows, |map| {
                let mut rows: Vec<_> = map.iter().filter(|(_, row)| filter(row)).collect();
                rows.sort_unstable_by(|(ka, a), (kb, b)| compare(a, b).then_with(|| ka.cmp(kb)));
                rows.into_iter().map(|(_, item)| item.clone()).collect()
            })
        });
        Self {
            scope: scope.clone(),
            rows,
            sorted,
            get_id: Rc::new(get_id),
        }
    }

    /// Reads a row, including filtered rows, from the current transaction context.
    pub fn get(&self, id: &K) -> Option<T> {
        self.scope.with(self.rows, |map| map.get(id).cloned())
    }

    /// Returns a snapshot of a sorted window.
    pub fn get_range(&self, offset: usize, limit: usize) -> Vec<T> {
        self.scope
            .with(self.sorted, |sorted| window(sorted, offset, limit))
    }

    /// Tracks an ordered window, including optimistic and draft changes.
    pub fn range_signal(&self, offset: usize, limit: usize) -> Computed<Vec<T>> {
        let sorted = self.sorted;
        self.scope
            .computed(move |cx| cx.with(sorted, |sorted| window(sorted, offset, limit)))
    }

    /// Applies a batch of row changes to the committed or active draft snapshot.
    pub fn edit(&self, edit: impl FnOnce(&mut RowEdit<'_, T, K>)) {
        self.scope.update(self.rows, |rows| {
            let mut next = rows.clone();
            edit(&mut RowEdit {
                rows: &mut next,
                get_id: &*self.get_id,
            });
            next
        });
    }

    /// Records a replayable row mutation on an existing optimistic layer.
    pub fn optimistic(
        &self,
        layer: &mut OptimisticLayer,
        edit: impl Fn(&mut RowEdit<'_, T, K>) + 'static,
    ) {
        let get_id = Rc::clone(&self.get_id);
        layer.update(self.rows, move |rows| {
            let mut next = rows.clone();
            edit(&mut RowEdit {
                rows: &mut next,
                get_id: &*get_id,
            });
            next
        });
    }
}

fn window<T: Clone>(sorted: &[T], offset: usize, limit: usize) -> Vec<T> {
    let start = offset.min(sorted.len());
    let end = start.saturating_add(limit).min(sorted.len());
    sorted[start..end].to_vec()
}