Skip to content

Rust: zwire Crates

For complete rustdoc signatures, trait bounds, and generated examples, see docs.rs/zwire.

  • Single-threaded arena (Scope, no_std + alloc):
    • Scope::new(), Scope::ssr(), Scope::with_mode(ScopeMode), scope.dispose(signal) -> bool, scope.dispose_id(id) -> bool, scope.dispose_scope(), scope.is_disposed()
    • scope.atom(val) / scope.atom_with(val, AtomOptions) -> Atom<T> (scope-bound Copy generational handle; NodeId / Signal<T>)
    • scope.computed(|cx| ...) / scope.computed_with(..., ComputedOptions) -> Computed<T> (scope-bound Copy; EvalContext with cx.peek / cx.try_peek), scope.projection(initial, |cx, draft| ...)
    • Auto-tracking effects & watchers: scope.effect(|cx| ...) -> Subscription (returns Option<CleanupFn>), scope.split_effect(track, run) -> Subscription, scope.watch(sig, cb, WatchOptions) -> Subscription, scope.subscribe_selected(sig, selector, listener) -> Subscription
    • Zero-Clone reads: scope.with(sig, |v| ...), scope.get_rc(sig), plus scope.get(sig) (T: Clone), scope.try_get(sig) -> Result<T, CoreError>, scope.peek(sig) / scope.try_peek(sig)
    • Writes & batching: scope.set(atom, val), scope.update(atom, |v| ...), scope.batch(|| ...), scope.batch_guard() -> BatchGuard<'_>, scope.untracked(|| ...)
    • Lifecycle & RAII guards (#[must_use]): scope.subscribe(sig, |v| ...) -> Subscription, scope.on_watched(sig, ...) -> HookGuard, scope.on_unwatched(sig, ...) -> HookGuard
    • Weak back-references: scope.downgrade() -> WeakScope
  • Thread-safe arena (SyncScope, feature = "sync", Send + Sync):
    • SyncScope::new(), SyncScope::ssr(), sync.dispose(signal) -> bool, sync.dispose_id(id) -> bool, sync.dispose_scope(), sync.is_disposed(), sync.downgrade() -> WeakSyncScope
    • sync.atom / atom_with (SyncAtomOptions) -> SyncAtom<T> / SyncSignal<T>, sync.computed / computed_with (SyncComputedOptions) -> SyncComputed<T> (SyncEvalContext with peek/try_peek), sync.effect (SyncCleanupFn), sync.split_effect, sync.watch, sync.subscribe_selected -> SyncSubscription
    • sync.get, sync.try_get, sync.peek, sync.try_peek, sync.get_arc, sync.with, sync.set, sync.update (optimistic retry), sync.try_update_once, sync.batch, sync.batch_guard() -> SyncBatchGuard<'_>, sync.subscribe, sync.on_watched / sync.on_unwatched -> SyncHookGuard, sync.has_commit_observers()
    • SyncAtomOptions::key assigns a protocol key. Register a WireCodec through register_sync_hydratable to encode and decode that atom.
    • The arena uses std::sync::RwLock for shared concurrent reads and releases locks before equality, replay, encoding and subscriber callbacks; Drop cleans up remaining hooks and owners. The sync feature requires std. The single-threaded Scope remains available with alloc on embedded targets.
  • Both scopes expose arena-backed owner() -> Owner / create_root() -> Owner (SyncOwner on SyncScope, identified by OwnerId) for lexical ownership trees with child_root(), on_cleanup(), effect(), subscribe(), and cascading LIFO disposal. changes(signal) returns a coalescing Changes (SyncChanges) snapshot stream. changed(signal).await waits once and drops its subscription. Snapshots use Rc<T> locally and Arc<T> across threads.
  • The facade exports zwire::optics::Lens<S, A> with borrowed field reads, focused updates, and a subscribable signal().
  • Errors: CoreError::{Cycle, Disposed, TypeMismatch} (unconditional core::error::Error) and ErrorSource.
  • OptimisticLayer: OptimisticLayer::new(&scope), update(atom, |v| ...), revert(), settle(), settle_with(|| ...), try_settle(|| -> Result<R, E>) (atomic DropGuard-backed rollback on both Err and panic).
  • OptimisticGuard (#[must_use]): RAII wrapper auto-reverting on drop / early ? return unless explicitly settled.
  • Draft (Detached STM): Draft::new(&scope), Draft::with_base(&scope, DraftBase::Committed | DraftBase::Effective), get, get_rc, with, set, update, run, commit(), commit_verified(), discard().
  • SyncOptimisticLayer and SyncOptimisticGuard rebase pure intents over concurrent authoritative writes. Stage server writes through layer.settle_with(|staged| staged.set(atom, value)).
  • SyncDraft::with_base selects committed or effective snapshots. get_arc shares values, set and update stage writes, and commit_verified validates all read versions and publishes the complete write set under one lock.
  • run_optimistic(&scope, apply, request, commit).await reverts on cancellation or request failure. run_sync_optimistic stages the authoritative response in a SyncSettlement.
  • Errors: DraftError::{Closed, StmConflict { node }, Core(CoreError)}.
  • Collection<T, K, Cmp, Flt, Sk = NoSortKey>: Standalone 2-level Chunked B-Tree (BLOCK_TARGET = 128, single-copy slot arena with NonZeroU64 revision niche — zero T: Clone required).
    • Constructors: Collection::new(get_id, compare) (using AcceptAll filter), Collection::with_filter(get_id, compare, filter) (ItemFilter), Collection::with_sort_key(get_id, sort_key) / Collection::with_sort_key_and_filter(get_id, sort_key, filter) (inline SortKey strategy: NoSortKey, CachedSortKey, BySortKey)
    • Mutations: insert, upsert, upsert_many, update_in_place, delete, clear
    • range(offset, limit) borrows a sorted window and skips complete blocks. iter_sorted() traverses the index. set_ordering(compare, filter) installs new predicates and preserves view handles.
    • Queries & incremental views: get, contains_key, len, indexed_len, top_k(k), watch_top_k(k) -> TopKViewId, unwatch_top_k(id), sync_view(id), view_items(id), view_mapped(id, f)
  • KeyedCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>: BTreeSet<(S, K, u32)>-backed incremental collection for pure Ord + Copy sort keys with O(1) Top-K boundary pruning (new, with_filter, from_parts, upsert, upsert_many, delete, clear, get, contains_key, len, is_empty, indexed_len, top_k, top_k_refs, watch_top_k, unwatch_top_k, sync_view, view_mapped, view_items, view_cloned).

With the facade’s sync and collections features, SyncReactiveCollection::new(&scope, id, compare) wraps RwLock<Collection<Arc<T>, K, ...>> for O(log N) multi-writer updates, filtered queries, O(1) Top-K boundary pruning (top_k_signal(k)), and range_signal(offset, limit) without full-map cloning (releasing locks before callbacks and SyncScope publication). For pure Ord + Copy sort keys, SyncPureReactiveCollection mirrors PureReactiveCollection on SyncScope backed directly by RwLock<KeyedCollection<Arc<T>, K, S, ...>> (new, with_filter, from_parts, upsert, upsert_many, update, delete, clear, get, contains_key, len, is_empty, indexed_len, get_top_k, top_k_signal, dispose_top_k_signal).

  • zwire-wasm (bridges/wasm): Wraps a Rust Scope in WireScope (WireScope::connect(&scope, peer), snapshot(), applyPatches(json) / apply_patches, takePatchBatch() / take_patch_batch), connecting to connectWasm(scope, peer) from @zwire/core/protocol/wasm. React order book example
  • zwire-serde (bridges/serde): Optional no_std + alloc serde bridge exporting to_wire, zero-copy borrowed from_wire<'de>, to_wire_json, from_wire_json, SerdeWire<T> (WireCodec, plus fallible try_to_wire), SerdeWireError, integer/boolean map keys, and #[serde(with)] modules wire_value and state_patch without adding serde to the core zwire workspace. Serde bridge guide
  • Zero-dep RFC-8259 JSON Codec: WireValue::{Null, Bool, Int(i64), Float(f64), String(String), Array(Vec<WireValue>), Object(BTreeMap<String, WireValue>)} with deterministic sorted-key to_json() and strict from_json() (JsonError, WireError), plus WireCodec trait (bool, 8–64-bit and pointer-sized signed/unsigned integers, f32, f64, String, Option<T>, Vec<T>, BTreeMap<String, T>, tuples of one to four items, and WireValue). Both i64 and u64 outside ±(2^53 - 1) emit decimal strings for lossless JS BigInt interop.
  • Enable the derive feature for #[derive(WireCodec)] on concrete named-field structs. Use #[wire(crate = zwire::protocol)] with the facade. Incoming objects must contain each declared field, and may contain additional fields.
  • Hydration: HydratedState, hydratable(&scope, key, initial), register_hydratable, dehydrate(&scope), dehydrate_json(&scope), hydrate(&scope, state), hydrate_json(&scope, json).
  • sync_hydratable, sync_hydrate, sync_hydrate_json, sync_dehydrate, and sync_dehydrate_json provide the same wire format on SyncScope. A checkpoint captures the committed values of all registered keys in one critical section before running codecs.
  • create_thread_sync_bridge(&scope, adapter) -> ThreadSyncBridge accepts a ThreadSyncAdapter. Writes from each thread coalesce at its outermost batch. The bridge serializes transport calls and rejects superseded revisions and recent duplicate transaction IDs.
  • from_sync_external_source (SyncExternalSource) polls unwatched snapshots and subscribes when watched. attach_sync_inspector (SyncInspectorHook, SyncInspectorGuard) observes commits, computations, flushes and errors. Commit callbacks run on the writer thread and carry per-atom base revisions for ordering.
  • External Sources: from_external_source(&scope, source) / from_external_source_with_eq implementing ExternalSource<T>.
  • Sync Bridge: create_sync_bridge(&scope, adapter: impl SyncAdapter, SyncBridgeOptions) -> RAII SyncBridge (pending_count(), flush(), dispose()); StatePatch (PatchOrigin::{Local, Remote}, slice_to_json, vec_from_json).
  • Inspector: attach_inspector(&scope, InspectorHook) -> HookGuard (on_write with WriteTraceEvent, on_compute with ComputeTraceEvent, on_flush with FlushTraceEvent, on_error).
  • Cargo features: default = ["std", "core", "sync", "tx", "collections", "protocol"].
    • Pure no_std + alloc / wasm32-unknown-unknown: default-features = false, features = ["core", "tx", "collections", "protocol"].
  • ReactiveCollection<T, K>: Bridges zwire-collections + zwire-core via Scope’s _flushHooks slot, exposing reactive col.top_k_signal(k) with 1x/batch coalesced materialization and STM Draft compatibility.
  • ReactiveCollection also exposes get_range, range_signal, iter_sorted, len_signal, indexed_len_signal, get_signal, has_signal, and set_ordering. Reactive reconfiguration accepts new closure types. Index policy callbacks run against detached values. A competing callback write wins, and try_upsert, try_upsert_many, or set_ordering returns false for the superseded edit.
  • TransactionalCollection::edit(|rows: &mut RowEdit<_, _>| ...) and optimistic(&mut layer, |rows| ...) support grouped row upserts, updates and deletions. A draft intercepts edit within draft.run. Each edit clones the row map once, and each optimistic callback reruns on authoritative changes.
  • PureReactiveCollection<T, K, S, IdFn, SkFn, Flt = AcceptAll>: High-frequency reactive collection backed directly by KeyedCollection for pure non-reentrant id, sort_key, and filter closures (new, with_filter, from_parts, upsert, upsert_many, delete, clear, get, contains_key, len, is_empty, indexed_len, get_top_k, top_k_signal, dispose_top_k_signal), releasing internal borrows before notifying Scope.
  • Stores & Projections (zwire::store, #[derive(ReactiveStore)] under derive feature): #[derive(ReactiveStore)] generates per-field Atom<Field> store structs (new, snapshot, patch, supporting #[store(crate = ...)]); MapStore<K, V> provides lazy per-key Atom<Option<V>> with on_unwatched pruning; projection(&scope, initial, |cx, draft| ...) provides mutable-draft incremental derived signals.
  • Executor-Agnostic #![no_std] Async Resources (zwire::resource): Resource<T, E, K> and ResourceState<T, E> (Pending, Refreshing(T), Ready(T), Error { error, previous }, Disposed) with monotonic generation stale-response rejection (refetch, mutate, latest, is_pending, load, drive).
  • zwire::prelude::*: Ergonomic re-export of all enabled crates’ primary types and functions.