zwire 0.3.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
//! Public Rust ecosystem integration cases, also run against packaged workspace crates.
#![cfg(all(feature = "core", feature = "protocol", feature = "tx"))]

use core::future::{Future, pending, ready};
use core::sync::atomic::{AtomicUsize, Ordering};
use core::task::{Context, Poll, Waker};
use std::sync::Arc;
use std::task::Wake;

use zwire::prelude::*;

#[derive(Default)]
struct Counter(AtomicUsize);
impl Wake for Counter {
    fn wake(self: Arc<Self>) {
        self.0.fetch_add(1, Ordering::Relaxed);
    }
}

#[test]
fn children_dispose_only_their_own_nodes() {
    let scope = Scope::new();
    let mut owner = scope.owner();
    let a = owner.atom(3);
    let b = {
        let mut child = owner.child();
        let b = child.computed(move |cx| 2 * cx.get(a));
        assert_eq!(scope.get(b), 6);
        b
    };
    assert_eq!(scope.try_get(b), Err(CoreError::Disposed));
    assert_eq!(scope.get(a), 3);
    owner.dispose();
    owner.dispose();
    assert_eq!(scope.live_node_count(), 0);
}

#[test]
fn changed_is_immediate_coalescing_and_disposal_wakes_a_pending_task() {
    let scope = Scope::new();
    let a = scope.atom(1);
    let mut changes = scope.changes(a);
    let woke = Arc::new(Counter::default());
    let waker = Waker::from(Arc::clone(&woke));
    let mut cx = Context::from_waker(&waker);
    assert!(changes.poll_next(&mut cx).is_pending());
    scope.set(a, 2);
    scope.set(a, 3);
    assert_eq!(woke.0.load(Ordering::Relaxed), 1);
    assert_eq!(
        changes.poll_next(&mut cx).map(|v| *v.unwrap().unwrap()),
        Poll::Ready(3)
    );
    assert!(changes.poll_next(&mut cx).is_pending());
    scope.dispose(a);
    assert_eq!(woke.0.load(Ordering::Relaxed), 2);
    assert_eq!(changes.poll_next(&mut cx), Poll::Ready(None));
    let ssr = Scope::ssr();
    let ssr_atom = ssr.atom(7);
    let mut silent = ssr.changes(ssr_atom);
    assert_eq!(silent.poll_next(&mut cx), Poll::Ready(None));
}

#[test]
fn optimistic_request_cancel_failure_and_authoritative_result() {
    let scope = Scope::new();
    let a = scope.atom(2);
    let apply = |g: &mut OptimisticGuard| g.update(a, |n| n + 3);
    let commit = |response: &i32| {
        scope.set(a, *response);
        Ok::<_, ()>(())
    };
    let mut cx = Context::from_waker(Waker::noop());
    let mut cancelled = Box::pin(run_optimistic(&scope, apply, pending(), commit));
    assert!(cancelled.as_mut().poll(&mut cx).is_pending());
    assert_eq!(scope.get(a), 5);
    scope.set(a, 10);
    assert_eq!(scope.get(a), 13);
    drop(cancelled);
    assert_eq!(scope.get(a), 10);
    let mut failed = Box::pin(run_optimistic(&scope, apply, ready(Err(())), commit));
    assert_eq!(failed.as_mut().poll(&mut cx), Poll::Ready(Err(())));
    assert_eq!(scope.get(a), 10);
    let mut done = Box::pin(run_optimistic(&scope, apply, ready(Ok(20)), commit));
    assert_eq!(done.as_mut().poll(&mut cx), Poll::Ready(Ok(20)));
    assert_eq!(scope.get(a), 20);
}

#[derive(Clone, PartialEq)]
struct Record {
    count: u8,
    active: bool,
}
struct Count;
impl Lens<Record, u8> for Count {
    fn view<'a>(&self, src: &'a Record) -> &'a u8 {
        &src.count
    }
    fn view_mut<'a>(&self, src: &'a mut Record) -> &'a mut u8 {
        &mut src.count
    }
}

#[test]
fn structural_lens_preserves_siblings() {
    let scope = Scope::new();
    let root = scope.atom(Record {
        count: 1,
        active: true,
    });
    let count = Count.signal(&scope, root);
    Count.update(&scope, root, |n| *n += 2);
    assert_eq!(scope.get(count), 3);
    assert_eq!(Count.with(&scope, root, |n| *n), 3);
    assert!(scope.with(root, |r| r.active));
}

#[cfg(feature = "derive")]
#[test]
fn derived_codec_roundtrips_nested_maps_tuples_and_lossless_integers() {
    use std::collections::BTreeMap;
    use zwire::protocol::WireError;
    #[derive(Debug, WireCodec, PartialEq)]
    #[wire(crate = zwire::protocol)]
    struct State {
        r#type: String,
        #[doc = "Nested generic commas must not be parsed as field boundaries."]
        readings: BTreeMap<String, (usize, f32, i8)>,
        short: Option<i16>,
    }
    let state = State {
        r#type: "sample".into(),
        readings: BTreeMap::from([("x".into(), (usize::MAX, 1.25, i8::MIN))]),
        short: None,
    };
    let wire = state.to_wire();
    let json = wire.to_json();
    assert_eq!(
        State::from_wire(&WireValue::from_json(&json).unwrap()),
        Ok(state)
    );
    assert_eq!(
        State::from_wire(&WireValue::object([])),
        Err(WireError::MissingField("type"))
    );
    assert_eq!(
        u8::from_wire(&WireValue::Int(256)),
        Err(WireError::OutOfRange)
    );
    assert_eq!(
        f32::from_wire(&WireValue::Float(f64::MAX)),
        Err(WireError::OutOfRange)
    );
    assert_eq!(WireValue::Int(12).as_f64(), Some(12.0));
    assert!(WireValue::Null.is_null());
}

#[cfg(feature = "sync")]
#[test]
fn sync_changes_and_optimistic_futures_cross_threads() {
    fn require_send<T: Send>(x: T) -> T {
        x
    }
    let scope = SyncScope::new();
    let mut owner = scope.owner();
    let a = owner.atom(2);
    let mut waiter = Box::pin(require_send(scope.changed(a)));
    let mut cx = Context::from_waker(Waker::noop());
    assert!(waiter.as_mut().poll(&mut cx).is_pending());
    std::thread::scope(|threads| {
        threads.spawn(|| scope.set(a, 4));
    });
    assert_eq!(
        waiter.as_mut().poll(&mut cx).map(|v| *v.unwrap().unwrap()),
        Poll::Ready(4)
    );
    let apply = |g: &mut SyncOptimisticGuard| g.update(a, |n| n + 1);
    let commit = |d: &mut SyncSettlement<'_>, n: &i32| d.set(a, *n);
    let mut cancelled = Box::pin(require_send(run_sync_optimistic(
        &scope,
        apply,
        pending::<Result<i32, DraftError>>(),
        commit,
    )));
    assert!(cancelled.as_mut().poll(&mut cx).is_pending());
    assert_eq!(scope.get(a), 5);
    drop(cancelled);
    assert_eq!(scope.get(a), 4);
    let mut done = Box::pin(require_send(run_sync_optimistic(
        &scope,
        apply,
        ready(Ok::<_, DraftError>(12)),
        commit,
    )));
    assert_eq!(done.as_mut().poll(&mut cx), Poll::Ready(Ok(12)));
    assert_eq!(scope.get(a), 12);
}