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
//! Immutable index snapshots let concurrent collection writers prepare comparisons and
//! filter decisions outside the scope lock and publish the entire index with a single CAS.
use alloc::{collections::BTreeMap, sync::Arc, vec::Vec};
use core::{cmp::Ordering, fmt};
use zwire_collections::{AcceptAll, ItemFilter};
use zwire_core::{SyncAtom, SyncAtomOptions, SyncComputed, SyncScope, WeakSyncScope};

#[derive(Clone, Debug)]
struct Rows<T, K> {
    items: BTreeMap<K, Arc<T>>,
    sorted: Vec<K>,
}

struct RowLifetime<T: Send + Sync + 'static, K: Send + Sync + 'static> {
    scope: WeakSyncScope,
    rows: SyncAtom<Rows<T, K>>,
}
impl<T: Send + Sync + 'static, K: Send + Sync + 'static> Drop for RowLifetime<T, K> {
    fn drop(&mut self) {
        if let Some(scope) = self.scope.upgrade() {
            scope.dispose(self.rows);
        }
    }
}

/// Thread-safe collection over a single versioned atom. Snapshots retain row payloads
/// by reference and copy the key index on edits. Queries refresh lazily in the scope.
pub struct SyncReactiveCollection<T, K, Id, Cmp, Flt = AcceptAll>
where
    T: Send + Sync + 'static,
    K: Send + Sync + 'static,
{
    scope: SyncScope,
    rows: SyncAtom<Rows<T, K>>,
    lifetime: Arc<RowLifetime<T, K>>,
    id: Id,
    cmp: Cmp,
    filter: Flt,
}

impl<T, K, Id, Cmp, Flt> fmt::Debug for SyncReactiveCollection<T, K, Id, Cmp, Flt>
where
    T: Send + Sync + 'static,
    K: Send + Sync + 'static,
{
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SyncReactiveCollection")
            .field("atom", &self.rows.id())
            .finish_non_exhaustive()
    }
}

impl<T, K, Id, Cmp> SyncReactiveCollection<T, K, Id, Cmp>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
    Id: Fn(&T) -> K + Send + Sync,
    Cmp: Fn(&T, &T) -> Ordering + Send + Sync,
{
    /// Creates a collection with every row indexed.
    pub fn new(scope: &SyncScope, id: Id, cmp: Cmp) -> Self {
        Self::with_filter(scope, id, cmp, AcceptAll)
    }
}

impl<T, K, Id, Cmp, Flt> SyncReactiveCollection<T, K, Id, Cmp, Flt>
where
    T: Clone + PartialEq + Send + Sync + 'static,
    K: Ord + Clone + Send + Sync + 'static,
    Id: Fn(&T) -> K + Send + Sync,
    Cmp: Fn(&T, &T) -> Ordering + Send + Sync,
    Flt: ItemFilter<T> + Send + Sync,
{
    /// Creates a filtered collection. Ties are broken by the extracted key.
    pub fn with_filter(scope: &SyncScope, id: Id, cmp: Cmp, filter: Flt) -> Self {
        let rows = scope.atom_with(
            Rows {
                items: BTreeMap::new(),
                sorted: Vec::new(),
            },
            SyncAtomOptions::new(),
        );
        Self {
            scope: scope.clone(),
            lifetime: Arc::new(RowLifetime {
                scope: scope.downgrade(),
                rows,
            }),
            rows,
            id,
            cmp,
            filter,
        }
    }
    /// Returns a zero-copy snapshot of an individual row.
    pub fn get(&self, key: &K) -> Option<Arc<T>> {
        self.scope.with(self.rows, |r| r.items.get(key).cloned())
    }
    /// Returns the total number of rows.
    pub fn len(&self) -> usize {
        self.scope.with(self.rows, |r| r.items.len())
    }
    /// Whether the collection has any rows.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }
    /// Returns the number of rows matching the index filter.
    pub fn indexed_len(&self) -> usize {
        self.scope.with(self.rows, |r| r.sorted.len())
    }
    /// Inserts or replaces a row. Concurrent edits rebase on the latest index snapshot.
    pub fn upsert(&self, item: T) {
        self.upsert_many(core::iter::once(item));
    }
    /// Atomically inserts or replaces a batch of rows.
    pub fn upsert_many(&self, items: impl IntoIterator<Item = T>) {
        let updates: Vec<_> = items
            .into_iter()
            .map(|item| ((self.id)(&item), Arc::new(item)))
            .collect();
        if updates.is_empty() {
            return;
        }
        self.scope.update(self.rows, |current| {
            let mut next = current.clone();
            for (key, item) in &updates {
                self.insert(&mut next, key, item);
            }
            next
        });
    }
    fn insert(&self, rows: &mut Rows<T, K>, key: &K, item: &Arc<T>) {
        if rows.items.contains_key(key) {
            rows.sorted.retain(|k| k != key);
        }
        if self.filter.matches(item) {
            let i = rows.sorted.partition_point(|k| {
                (self.cmp)(&rows.items[k], item).then_with(|| k.cmp(key)) == Ordering::Less
            });
            rows.sorted.insert(i, key.clone());
        }
        rows.items.insert(key.clone(), Arc::clone(item));
    }
    /// Updates a detached snapshot and migrates changed keys. Returns false if the
    /// original row was removed or replaced before publication.
    pub fn update(&self, key: &K, f: impl FnOnce(&T) -> T) -> bool {
        let Some(original) = self.get(key) else {
            return false;
        };
        let item = Arc::new(f(&original));
        let next_key = (self.id)(&item);
        loop {
            let Ok(snapshot) = self.scope.atom_snapshot(self.rows.id()) else {
                return false;
            };
            let current = snapshot
                .committed()
                .downcast_ref::<Rows<T, K>>()
                .expect("collection rows");
            if !current
                .items
                .get(key)
                .is_some_and(|row| Arc::ptr_eq(row, &original))
            {
                return false;
            }
            let mut next = current.clone();
            if &next_key != key {
                next.items.remove(key);
                next.sorted.retain(|k| k != key);
            }
            self.insert(&mut next, &next_key, &item);
            let change = snapshot.with_base(Arc::new(next)).expect("collection rows");
            match self
                .scope
                .publish_atoms(core::slice::from_ref(&change), &[], false)
            {
                Ok(None) => return true,
                Err(_) => return false,
                Ok(Some(_)) => {}
            }
        }
    }
    /// Deletes a row, returning the removed payload.
    pub fn delete(&self, key: &K) -> Option<Arc<T>> {
        loop {
            let snapshot = self.scope.atom_snapshot(self.rows.id()).ok()?;
            let current = snapshot
                .committed()
                .downcast_ref::<Rows<T, K>>()
                .expect("collection rows");
            let removed = Arc::clone(current.items.get(key)?);
            let mut next = current.clone();
            next.items.remove(key);
            next.sorted.retain(|id| id != key);
            let change = snapshot.with_base(Arc::new(next)).expect("collection rows");
            if self
                .scope
                .publish_atoms(core::slice::from_ref(&change), &[], false)
                .ok()?
                .is_none()
            {
                return Some(removed);
            }
        }
    }
    /// Clears all rows and the sorted index.
    pub fn clear(&self) {
        self.scope.set(
            self.rows,
            Rows {
                items: BTreeMap::new(),
                sorted: Vec::new(),
            },
        );
    }
    /// An exact, deterministically sorted Top-K signal with equality cutoff.
    pub fn top_k_signal(&self, k: usize) -> SyncComputed<Vec<T>> {
        self.range_signal(0, k)
    }
    /// A sorted offset/limit window signal.
    pub fn range_signal(&self, offset: usize, limit: usize) -> SyncComputed<Vec<T>> {
        let lifetime = Arc::clone(&self.lifetime);
        self.scope.computed(move |cx| {
            cx.with(lifetime.rows, |r| {
                r.sorted
                    .iter()
                    .skip(offset)
                    .take(limit)
                    .map(|k| (*r.items[k]).clone())
                    .collect()
            })
        })
    }
}