Skip to main content

sui_reactive/
lib.rs

1#![forbid(unsafe_code)]
2
3//! Architecture-neutral observable values for SUI.
4//!
5//! This crate owns state and change notification only. It does not depend on
6//! the SUI widget runtime, so applications may adapt other stores through
7//! [`Observable`] without adopting a SUI-owned application architecture.
8//!
9//! # Threads
10//!
11//! [`Signal`] is `Send + Sync` when its value is, and may be written from any
12//! thread. Observer callbacks run synchronously **on the thread that wrote the
13//! value**, after the value lock is released and before the write returns.
14//! Inside [`batch`], they run on the batching thread when the outermost batch
15//! ends. This crate never moves an observer call to another thread.
16//!
17//! Observers therefore must be cheap, non-blocking, and safe to run on a
18//! worker. The SUI runtime's widget observers only enqueue an invalidation and
19//! wake the event loop; widgets re-read the value later on the UI thread.
20//! Custom observers that need UI-thread state should forward a message (for
21//! example through SUI's `UiHandle`) instead of touching that state directly.
22//!
23//! A value read inside an observer may already be newer than the
24//! [`Change::version`] it received if another thread wrote concurrently.
25//! Observers may write back to the signal that notified them.
26//!
27//! # Large values
28//!
29//! [`Signal::get`] clones the value and [`Signal::update`] clones it to
30//! compare. For large state, read with [`Signal::with`], mutate with
31//! [`Signal::modify`] or [`Signal::mark_changed`], or store an `Arc<T>` and
32//! use [`Signal::set_arc`] and [`Signal::modify_arc`], which compare pointers
33//! and copy only while a reader still holds the previous snapshot.
34
35mod batch;
36mod combine;
37mod task;
38
39use std::{
40    fmt,
41    future::Future,
42    marker::PhantomData,
43    ops::{Deref, DerefMut},
44    pin::Pin,
45    sync::{
46        Arc, Mutex, RwLock, RwLockReadGuard, RwLockWriteGuard, Weak,
47        atomic::{AtomicU64, Ordering},
48    },
49    task::{Context, Poll, Waker},
50};
51
52pub use batch::batch;
53pub use combine::{Zip, combine, combine_named};
54pub use task::{Task, TaskHandle, TaskState};
55
56static NEXT_SOURCE_ID: AtomicU64 = AtomicU64::new(1);
57
58/// Stable identity for one observable source.
59#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
60pub struct SourceId(u64);
61
62impl SourceId {
63    pub const fn get(self) -> u64 {
64        self.0
65    }
66
67    /// Allocate a process-unique observable source identifier.
68    pub fn new() -> Self {
69        Self(NEXT_SOURCE_ID.fetch_add(1, Ordering::Relaxed))
70    }
71}
72
73impl Default for SourceId {
74    fn default() -> Self {
75        Self::new()
76    }
77}
78
79/// Metadata emitted when an observable value changes.
80#[derive(Debug, Clone, PartialEq, Eq)]
81pub struct Change {
82    pub source_id: SourceId,
83    pub source_name: Arc<str>,
84    pub version: u64,
85}
86
87type ObserverCallback = dyn Fn(Change) + Send + Sync + 'static;
88
89struct ObserverInner {
90    callback: Box<ObserverCallback>,
91}
92
93/// Cloneable change observer used by observable implementations.
94///
95/// The callback runs on the thread that changed the observed value; see the
96/// [crate-level threading notes](crate#threads).
97#[derive(Clone)]
98pub struct Observer {
99    inner: Arc<ObserverInner>,
100}
101
102impl Observer {
103    pub fn new(callback: impl Fn(Change) + Send + Sync + 'static) -> Self {
104        Self {
105            inner: Arc::new(ObserverInner {
106                callback: Box::new(callback),
107            }),
108        }
109    }
110
111    pub fn notify(&self, change: Change) {
112        (self.inner.callback)(change);
113    }
114
115    pub fn downgrade(&self) -> WeakObserver {
116        WeakObserver {
117            inner: Arc::downgrade(&self.inner),
118        }
119    }
120}
121
122impl fmt::Debug for Observer {
123    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
124        formatter.debug_struct("Observer").finish_non_exhaustive()
125    }
126}
127
128/// Weak observer reference suitable for storage inside custom observables.
129#[derive(Clone)]
130pub struct WeakObserver {
131    inner: Weak<ObserverInner>,
132}
133
134impl WeakObserver {
135    /// Notify the observer, returning `false` after its subscription was
136    /// dropped.
137    pub fn notify(&self, change: Change) -> bool {
138        let Some(observer) = self.inner.upgrade() else {
139            return false;
140        };
141        (observer.callback)(change);
142        true
143    }
144}
145
146impl fmt::Debug for WeakObserver {
147    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
148        formatter
149            .debug_struct("WeakObserver")
150            .finish_non_exhaustive()
151    }
152}
153
154/// Keeps an observable subscription alive.
155///
156/// Dropping the guard releases the strong observer reference. Sources retain
157/// only weak references and prune them during later notifications.
158pub struct Subscription {
159    // Dropped before `_release`, so the release hook sees the observer gone.
160    _observer: Observer,
161    _release: Option<Box<dyn Send + Sync>>,
162}
163
164impl Subscription {
165    pub fn new(observer: Observer) -> Self {
166        Self {
167            _observer: observer,
168            _release: None,
169        }
170    }
171
172    /// Keep `release` alive with the subscription and drop it right after the
173    /// observer, e.g. to tear down upstream work once nobody is listening.
174    pub fn with_release(observer: Observer, release: impl Send + Sync + 'static) -> Self {
175        Self {
176            _observer: observer,
177            _release: Some(Box::new(release)),
178        }
179    }
180}
181
182impl fmt::Debug for Subscription {
183    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
184        formatter
185            .debug_struct("Subscription")
186            .finish_non_exhaustive()
187    }
188}
189
190/// Readable value that can notify subscribers after meaningful changes.
191///
192/// SUI's runtime consumes this trait, so applications may provide adapters for
193/// reducer stores, channels, actor snapshots, or other state architectures.
194///
195/// The simplest custom implementation keeps a `Signal<u64>` revision next to
196/// its data, calls [`Signal::mark_changed`] after each change, and delegates
197/// `source_id`, `source_name`, `subscribe`, and `value_version` to it. That
198/// gives it batching and observer pruning for free.
199pub trait Observable<T> {
200    fn source_id(&self) -> SourceId;
201    fn source_name(&self) -> Arc<str>;
202    fn get(&self) -> T;
203    fn subscribe(&self, observer: Observer) -> Subscription;
204
205    /// Call `reader` once with a borrow of the current value.
206    ///
207    /// The default clones through [`get`](Self::get). Implementations that
208    /// store the value should override it to avoid the copy; selectors read
209    /// their source through this method.
210    fn read(&self, reader: &mut dyn FnMut(&T)) {
211        reader(&self.get());
212    }
213
214    /// A counter identifying the current value, or `None` if unknown.
215    ///
216    /// Selectors use it to reuse a derived value while the source has not
217    /// changed. It must increase *after* every change to the value, so that a
218    /// version read before [`read`](Self::read) never claims a newer value
219    /// than the one read. Return `None` if that cannot be guaranteed.
220    fn value_version(&self) -> Option<u64> {
221        None
222    }
223
224    /// A future that resolves with the next change notification after this
225    /// call. It subscribes immediately, so a change made before the first
226    /// poll is not missed. It needs no particular executor.
227    fn changed(&self) -> Changed
228    where
229        Self: Sized,
230    {
231        Changed::new(|observer| self.subscribe(observer))
232    }
233}
234
235/// Future returned by [`Observable::changed`] and [`Signal::changed`].
236///
237/// Resolves with the most recent [`Change`] once at least one has arrived.
238/// Dropping it unsubscribes.
239#[must_use = "futures do nothing unless awaited"]
240pub struct Changed {
241    state: Arc<Mutex<ChangedState>>,
242    _subscription: Subscription,
243}
244
245#[derive(Default)]
246struct ChangedState {
247    change: Option<Change>,
248    waker: Option<Waker>,
249}
250
251impl Changed {
252    fn new(subscribe: impl FnOnce(Observer) -> Subscription) -> Self {
253        let state = Arc::new(Mutex::new(ChangedState::default()));
254        let observed = Arc::clone(&state);
255        let subscription = subscribe(Observer::new(move |change| {
256            let waker = {
257                let mut state = lock(&observed);
258                state.change = Some(change);
259                state.waker.take()
260            };
261            if let Some(waker) = waker {
262                waker.wake();
263            }
264        }));
265        Self {
266            state,
267            _subscription: subscription,
268        }
269    }
270}
271
272impl Future for Changed {
273    type Output = Change;
274
275    fn poll(self: Pin<&mut Self>, context: &mut Context<'_>) -> Poll<Change> {
276        let mut state = lock(&self.state);
277        if let Some(change) = state.change.take() {
278            return Poll::Ready(change);
279        }
280        if !state
281            .waker
282            .as_ref()
283            .is_some_and(|waker| waker.will_wake(context.waker()))
284        {
285            state.waker = Some(context.waker().clone());
286        }
287        Poll::Pending
288    }
289}
290
291impl fmt::Debug for Changed {
292    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
293        formatter.debug_struct("Changed").finish_non_exhaustive()
294    }
295}
296
297fn read_with<T, R, O>(observable: &O, read: impl FnOnce(&T) -> R) -> R
298where
299    O: Observable<T> + ?Sized,
300{
301    let mut read = Some(read);
302    let mut result = None;
303    observable.read(&mut |value| {
304        if let Some(read) = read.take() {
305            result = Some(read(value));
306        }
307    });
308    result.expect("Observable::read must call its reader")
309}
310
311/// Identity, revision, and observers of one signal. Kept apart from the value
312/// so [`batch`] can queue a deferred notification without knowing its type.
313pub(crate) struct SignalCore {
314    id: SourceId,
315    name: Arc<str>,
316    version: AtomicU64,
317    observers: Mutex<Vec<Weak<ObserverInner>>>,
318}
319
320impl SignalCore {
321    fn new(name: Arc<str>) -> Arc<Self> {
322        Arc::new(Self {
323            id: SourceId::new(),
324            name,
325            version: AtomicU64::new(0),
326            observers: Mutex::new(Vec::new()),
327        })
328    }
329
330    fn changed(self: &Arc<Self>) {
331        self.version.fetch_add(1, Ordering::AcqRel);
332        self.notify();
333    }
334
335    fn notify(self: &Arc<Self>) {
336        if !batch::defer(self) {
337            self.deliver();
338        }
339    }
340
341    fn version(&self) -> u64 {
342        self.version.load(Ordering::Acquire)
343    }
344
345    fn add_observer(&self, observer: &Observer) {
346        lock(&self.observers).push(Arc::downgrade(&observer.inner));
347    }
348
349    /// Prune dropped observers and report whether any remain.
350    fn has_observers(&self) -> bool {
351        let mut observers = lock(&self.observers);
352        observers.retain(|observer| observer.strong_count() > 0);
353        !observers.is_empty()
354    }
355
356    pub(crate) fn source_id(&self) -> SourceId {
357        self.id
358    }
359
360    pub(crate) fn deliver(&self) {
361        let change = Change {
362            source_id: self.id,
363            source_name: Arc::clone(&self.name),
364            version: self.version.load(Ordering::Acquire),
365        };
366        let observers = {
367            let mut observers = lock(&self.observers);
368            let mut live = Vec::with_capacity(observers.len());
369            observers.retain(|observer| {
370                if let Some(observer) = observer.upgrade() {
371                    live.push(observer);
372                    true
373                } else {
374                    false
375                }
376            });
377            live
378        };
379        for observer in observers {
380            (observer.callback)(change.clone());
381        }
382    }
383}
384
385struct SignalInner<T> {
386    core: Arc<SignalCore>,
387    value: RwLock<T>,
388}
389
390/// Cloneable observable storage with equality-deduplicated writes.
391///
392/// Every write that changes the value increments [`version`](Self::version)
393/// and notifies observers on the writing thread (see the
394/// [crate-level threading notes](crate#threads)).
395///
396/// Closures passed to [`with`](Self::with), [`update`](Self::update), and
397/// [`modify`](Self::modify) run while the value is locked, so they must not
398/// write to the same signal. Debug builds panic, naming the signal, instead
399/// of deadlocking.
400pub struct Signal<T> {
401    inner: Arc<SignalInner<T>>,
402}
403
404impl<T> Clone for Signal<T> {
405    fn clone(&self) -> Self {
406        Self {
407            inner: Arc::clone(&self.inner),
408        }
409    }
410}
411
412impl<T> fmt::Debug for Signal<T>
413where
414    T: fmt::Debug,
415{
416    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
417        formatter
418            .debug_struct("Signal")
419            .field("id", &self.inner.core.id)
420            .field("name", &self.inner.core.name)
421            .field("value", &*self.read_lock())
422            .field("version", &self.version())
423            .finish()
424    }
425}
426
427impl<T> Signal<T> {
428    pub fn new(value: T) -> Self {
429        Self::named("Signal", value)
430    }
431
432    pub fn named(name: impl Into<Arc<str>>, value: T) -> Self {
433        Self {
434            inner: Arc::new(SignalInner {
435                core: SignalCore::new(name.into()),
436                value: RwLock::new(value),
437            }),
438        }
439    }
440
441    pub fn source_id(&self) -> SourceId {
442        self.inner.core.id
443    }
444
445    pub fn source_name(&self) -> Arc<str> {
446        Arc::clone(&self.inner.core.name)
447    }
448
449    /// Revision counter, incremented by every write that notifies.
450    pub fn version(&self) -> u64 {
451        self.inner.core.version()
452    }
453
454    /// Clone the current value. Prefer [`with`](Self::with) for large values.
455    pub fn get(&self) -> T
456    where
457        T: Clone,
458    {
459        self.read_lock().clone()
460    }
461
462    /// Read the current value by reference without cloning it.
463    pub fn with<R>(&self, read: impl FnOnce(&T) -> R) -> R {
464        read(&self.read_lock())
465    }
466
467    pub fn set(&self, value: T) -> bool
468    where
469        T: PartialEq,
470    {
471        {
472            let mut current = self.write_lock();
473            if *current == value {
474                return false;
475            }
476            *current = value;
477        }
478        self.inner.core.changed();
479        true
480    }
481
482    /// Mutate the value and notify if it differs from before.
483    ///
484    /// This clones the value to compare it. For large values use
485    /// [`modify`](Self::modify), which lets the closure report the change.
486    pub fn update(&self, update: impl FnOnce(&mut T)) -> bool
487    where
488        T: Clone + PartialEq,
489    {
490        {
491            let mut current = self.write_lock();
492            let previous = current.clone();
493            update(&mut current);
494            if *current == previous {
495                return false;
496            }
497        }
498        self.inner.core.changed();
499        true
500    }
501
502    /// Mutate the value in place without cloning or comparing it.
503    ///
504    /// Observers are notified only when `modify` returns `true`.
505    pub fn modify(&self, modify: impl FnOnce(&mut T) -> bool) -> bool {
506        let changed = modify(&mut self.write_lock());
507        if changed {
508            self.inner.core.changed();
509        }
510        changed
511    }
512
513    /// Increment the version and notify observers without touching the value.
514    ///
515    /// Use after changing state the signal cannot see, such as data behind
516    /// interior mutability, or as a revision bump for values without cheap
517    /// equality.
518    pub fn mark_changed(&self) {
519        self.inner.core.changed();
520    }
521
522    /// Observe changes. Unlike [`Observable::subscribe`], this does not
523    /// require `T: Clone`.
524    pub fn subscribe(&self, observer: Observer) -> Subscription {
525        self.inner.core.add_observer(&observer);
526        Subscription::new(observer)
527    }
528
529    /// A future that resolves at the next change; see [`Observable::changed`].
530    /// Unlike the trait method, this does not require `T: Clone`.
531    pub fn changed(&self) -> Changed {
532        Changed::new(|observer| self.subscribe(observer))
533    }
534
535    pub fn select<U>(
536        &self,
537        select: impl Fn(&T) -> U + Send + Sync + 'static,
538    ) -> Selector<Self, T, U>
539    where
540        T: Clone + Send + Sync + 'static,
541        U: Clone + PartialEq + Send + Sync + 'static,
542    {
543        self.select_named("Selector", select)
544    }
545
546    pub fn select_named<U>(
547        &self,
548        name: impl Into<Arc<str>>,
549        select: impl Fn(&T) -> U + Send + Sync + 'static,
550    ) -> Selector<Self, T, U>
551    where
552        T: Clone + Send + Sync + 'static,
553        U: Clone + PartialEq + Send + Sync + 'static,
554    {
555        Selector::new(name, self.clone(), select)
556    }
557
558    fn read_lock(&self) -> Held<RwLockReadGuard<'_, T>> {
559        let held = HeldLock::acquire(&self.inner.core, false);
560        Held {
561            guard: self
562                .inner
563                .value
564                .read()
565                .unwrap_or_else(std::sync::PoisonError::into_inner),
566            _held: held,
567        }
568    }
569
570    fn write_lock(&self) -> Held<RwLockWriteGuard<'_, T>> {
571        let held = HeldLock::acquire(&self.inner.core, true);
572        Held {
573            guard: self
574                .inner
575                .value
576                .write()
577                .unwrap_or_else(std::sync::PoisonError::into_inner),
578            _held: held,
579        }
580    }
581}
582
583/// A signal value guard plus its debug-build lock record.
584struct Held<G> {
585    // Unlock before forgetting the record.
586    guard: G,
587    _held: HeldLock,
588}
589
590impl<G: Deref> Deref for Held<G> {
591    type Target = G::Target;
592
593    fn deref(&self) -> &G::Target {
594        &self.guard
595    }
596}
597
598impl<G: DerefMut> DerefMut for Held<G> {
599    fn deref_mut(&mut self) -> &mut G::Target {
600        &mut self.guard
601    }
602}
603
604#[cfg(debug_assertions)]
605thread_local! {
606    /// Signals whose value this thread has locked, and whether for writing.
607    static HELD_LOCKS: std::cell::RefCell<Vec<(SourceId, bool)>> =
608        const { std::cell::RefCell::new(Vec::new()) };
609}
610
611/// In debug builds, turns a same-thread re-entry that would deadlock on the
612/// value lock into a panic naming the signal. Free in release builds.
613struct HeldLock {
614    #[cfg(debug_assertions)]
615    id: SourceId,
616}
617
618impl HeldLock {
619    #[cfg_attr(not(debug_assertions), allow(unused_variables))]
620    fn acquire(core: &SignalCore, write: bool) -> Self {
621        #[cfg(debug_assertions)]
622        {
623            let conflict = HELD_LOCKS
624                .try_with(|held| {
625                    let mut held = held.borrow_mut();
626                    let conflict = held
627                        .iter()
628                        .any(|&(id, held_write)| id == core.id && (write || held_write));
629                    if !conflict {
630                        held.push((core.id, write));
631                    }
632                    conflict
633                })
634                .unwrap_or(false);
635            if conflict {
636                panic!(
637                    "signal `{}` was {} while this thread already holds its value inside \
638                     `with`, `update`, `modify`, or a selector; this would deadlock",
639                    core.name,
640                    if write { "written" } else { "read" },
641                );
642            }
643            Self { id: core.id }
644        }
645        #[cfg(not(debug_assertions))]
646        Self {}
647    }
648}
649
650#[cfg(debug_assertions)]
651impl Drop for HeldLock {
652    fn drop(&mut self) {
653        let _ = HELD_LOCKS.try_with(|held| {
654            let mut held = held.borrow_mut();
655            if let Some(index) = held.iter().rposition(|&(id, _)| id == self.id) {
656                held.remove(index);
657            }
658        });
659    }
660}
661
662impl<T> Signal<Arc<T>> {
663    /// Replace the shared value, deduplicating by pointer rather than by
664    /// value equality. [`get`](Self::get) then only clones the `Arc`.
665    pub fn set_arc(&self, value: Arc<T>) -> bool {
666        {
667            let mut current = self.write_lock();
668            if Arc::ptr_eq(&current, &value) {
669                return false;
670            }
671            *current = value;
672        }
673        self.inner.core.changed();
674        true
675    }
676
677    /// Mutate the shared value through [`Arc::make_mut`]: in place when no
678    /// reader holds the current snapshot, otherwise on a fresh copy so the
679    /// snapshots readers hold stay unchanged.
680    ///
681    /// Observers are notified only when `modify` returns `true`.
682    pub fn modify_arc(&self, modify: impl FnOnce(&mut T) -> bool) -> bool
683    where
684        T: Clone,
685    {
686        self.modify(|value| modify(Arc::make_mut(value)))
687    }
688}
689
690impl<T> Observable<T> for Signal<T>
691where
692    T: Clone + 'static,
693{
694    fn source_id(&self) -> SourceId {
695        self.source_id()
696    }
697
698    fn source_name(&self) -> Arc<str> {
699        self.source_name()
700    }
701
702    fn get(&self) -> T {
703        self.get()
704    }
705
706    fn read(&self, reader: &mut dyn FnMut(&T)) {
707        self.with(|value| reader(value));
708    }
709
710    fn value_version(&self) -> Option<u64> {
711        Some(self.version())
712    }
713
714    fn subscribe(&self, observer: Observer) -> Subscription {
715        self.subscribe(observer)
716    }
717}
718
719struct SelectorInner<S, I, O> {
720    name: Arc<str>,
721    source: S,
722    select: Box<dyn Fn(&I) -> O + Send + Sync>,
723    /// Downstream observers and this selector's own change version.
724    core: Arc<SignalCore>,
725    /// Last derived value, keyed by the source's value version.
726    cached: Mutex<Option<(u64, O)>>,
727    tracking: Mutex<Tracking<O>>,
728    _input: PhantomData<fn(I)>,
729}
730
731/// The single upstream subscription shared by every downstream observer.
732struct Tracking<O> {
733    upstream: Option<Subscription>,
734    /// Value most recently delivered to observers, for deduplication.
735    delivered: Option<O>,
736}
737
738/// Equality-deduplicated derived observable.
739///
740/// Clones share one upstream subscription and one cached value: however many
741/// widgets observe a selector, `select` runs once per source change, and
742/// [`get`](Observable::get) reuses the last result while the source's
743/// [`value_version`](Observable::value_version) is unchanged. The upstream
744/// subscription is released when the last downstream subscription drops.
745///
746/// The source is read by reference through [`Observable::read`], so selecting
747/// a small field from a large [`Signal`] does not clone the whole value. The
748/// select closure runs while the source is locked and must not write to it.
749pub struct Selector<S, I, O> {
750    inner: Arc<SelectorInner<S, I, O>>,
751}
752
753impl<S, I, O> Clone for Selector<S, I, O> {
754    fn clone(&self) -> Self {
755        Self {
756            inner: Arc::clone(&self.inner),
757        }
758    }
759}
760
761impl<S, I, O> Selector<S, I, O> {
762    pub fn new(
763        name: impl Into<Arc<str>>,
764        source: S,
765        select: impl Fn(&I) -> O + Send + Sync + 'static,
766    ) -> Self {
767        let name = name.into();
768        Self {
769            inner: Arc::new(SelectorInner {
770                core: SignalCore::new(Arc::clone(&name)),
771                name,
772                source,
773                select: Box::new(select),
774                cached: Mutex::new(None),
775                tracking: Mutex::new(Tracking {
776                    upstream: None,
777                    delivered: None,
778                }),
779                _input: PhantomData,
780            }),
781        }
782    }
783}
784
785impl<S, I, O> SelectorInner<S, I, O>
786where
787    S: Observable<I>,
788    O: Clone + PartialEq,
789{
790    fn compute(&self) -> O {
791        // Read the version first: the value read after it is at least as new.
792        let version = self.source.value_version();
793        if let Some(version) = version
794            && let Some((cached_version, value)) = &*lock(&self.cached)
795            && *cached_version == version
796        {
797            return value.clone();
798        }
799        let value = read_with(&self.source, |input| (self.select)(input));
800        if let Some(version) = version {
801            let mut cached = lock(&self.cached);
802            if cached
803                .as_ref()
804                .is_none_or(|(cached_version, _)| *cached_version <= version)
805            {
806                *cached = Some((version, value.clone()));
807            }
808        }
809        value
810    }
811
812    fn source_changed(&self) {
813        {
814            let mut tracking = lock(&self.tracking);
815            if tracking.upstream.is_none() {
816                return; // Released while this notification was in flight.
817            }
818            // Derive and compare under one lock so concurrent writers cannot
819            // store an older value after a newer one.
820            let next = self.compute();
821            if tracking.delivered.as_ref() == Some(&next) {
822                return;
823            }
824            tracking.delivered = Some(next);
825            self.core.version.fetch_add(1, Ordering::AcqRel);
826        }
827        // Observers may write back to the source and reenter this selector.
828        self.core.notify();
829    }
830}
831
832/// Drops the shared upstream subscription with the last downstream one.
833struct SelectorRelease<S, I, O> {
834    inner: Arc<SelectorInner<S, I, O>>,
835}
836
837impl<S, I, O> Drop for SelectorRelease<S, I, O> {
838    fn drop(&mut self) {
839        let upstream = {
840            let mut tracking = lock(&self.inner.tracking);
841            if self.inner.core.has_observers() {
842                return;
843            }
844            tracking.delivered = None;
845            tracking.upstream.take()
846        };
847        drop(upstream);
848    }
849}
850
851impl<S, I, O> Observable<O> for Selector<S, I, O>
852where
853    S: Observable<I> + Send + Sync + 'static,
854    I: Send + Sync + 'static,
855    O: Clone + PartialEq + Send + Sync + 'static,
856{
857    fn source_id(&self) -> SourceId {
858        self.inner.core.id
859    }
860
861    fn source_name(&self) -> Arc<str> {
862        Arc::clone(&self.inner.name)
863    }
864
865    fn get(&self) -> O {
866        self.inner.compute()
867    }
868
869    fn value_version(&self) -> Option<u64> {
870        // A pure function of the source changes only when the source does.
871        self.inner.source.value_version()
872    }
873
874    fn subscribe(&self, observer: Observer) -> Subscription {
875        {
876            let mut tracking = lock(&self.inner.tracking);
877            self.inner.core.add_observer(&observer);
878            if tracking.upstream.is_none() {
879                let selector = Arc::downgrade(&self.inner);
880                tracking.upstream = Some(self.inner.source.subscribe(Observer::new(move |_| {
881                    if let Some(selector) = selector.upgrade() {
882                        selector.source_changed();
883                    }
884                })));
885                // Subscribed first, so a write racing this read is either
886                // included here or delivered afterwards.
887                tracking.delivered = Some(self.inner.compute());
888            }
889        }
890        Subscription::with_release(
891            observer,
892            SelectorRelease {
893                inner: Arc::clone(&self.inner),
894            },
895        )
896    }
897}
898
899pub(crate) fn lock<T>(mutex: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
900    mutex
901        .lock()
902        .unwrap_or_else(std::sync::PoisonError::into_inner)
903}
904
905#[cfg(test)]
906mod tests {
907    use super::*;
908    use std::sync::atomic::AtomicUsize;
909
910    fn counter<O: Observable<T>, T>(observable: &O) -> (Arc<AtomicUsize>, Subscription) {
911        let notifications = Arc::new(AtomicUsize::new(0));
912        let count = Arc::clone(&notifications);
913        let subscription = observable.subscribe(Observer::new(move |_| {
914            count.fetch_add(1, Ordering::Relaxed);
915        }));
916        (notifications, subscription)
917    }
918
919    #[test]
920    fn signal_notifies_only_for_meaningful_changes() {
921        let signal = Signal::named("count", 1usize);
922        let (notifications, _subscription) = counter(&signal);
923
924        assert!(!signal.set(1));
925        assert!(signal.set(2));
926        assert_eq!(notifications.load(Ordering::Relaxed), 1);
927        assert_eq!(signal.version(), 1);
928    }
929
930    #[test]
931    fn modify_and_mark_changed_notify_without_clone_or_comparison() {
932        // Neither Clone nor PartialEq.
933        struct Big(Vec<u8>);
934
935        let signal = Signal::new(Big(vec![0; 1024]));
936        let notifications = Arc::new(AtomicUsize::new(0));
937        let count = Arc::clone(&notifications);
938        let _subscription = signal.subscribe(Observer::new(move |_| {
939            count.fetch_add(1, Ordering::Relaxed);
940        }));
941
942        assert!(!signal.modify(|big| {
943            big.0[0] = 0;
944            false
945        }));
946        assert!(signal.modify(|big| {
947            big.0[0] = 7;
948            true
949        }));
950        signal.mark_changed();
951        assert_eq!(signal.with(|big| big.0[0]), 7);
952        assert_eq!(notifications.load(Ordering::Relaxed), 2);
953        assert_eq!(signal.version(), 2);
954    }
955
956    #[test]
957    fn arc_signal_uses_pointer_identity_and_copies_on_write() {
958        let signal = Signal::new(Arc::new(vec![1, 2, 3]));
959        let (notifications, _subscription) = counter(&signal);
960
961        let same = signal.get();
962        assert!(!signal.set_arc(Arc::clone(&same)));
963        // Equal contents, different allocation: a deliberate replacement.
964        assert!(signal.set_arc(Arc::new(vec![1, 2, 3])));
965        assert_eq!(notifications.load(Ordering::Relaxed), 1);
966
967        let snapshot = signal.get();
968        assert!(signal.modify_arc(|values| {
969            values.push(4);
970            true
971        }));
972        assert_eq!(*snapshot, vec![1, 2, 3]);
973        assert_eq!(*signal.get(), vec![1, 2, 3, 4]);
974
975        drop(snapshot);
976        let before = Arc::as_ptr(&signal.get());
977        signal.modify_arc(|values| {
978            values.push(5);
979            true
980        });
981        assert_eq!(Arc::as_ptr(&signal.get()), before, "mutated in place");
982        assert_eq!(notifications.load(Ordering::Relaxed), 3);
983    }
984
985    #[test]
986    fn selector_reads_source_without_cloning_it() {
987        static CLONES: AtomicUsize = AtomicUsize::new(0);
988
989        #[derive(PartialEq)]
990        struct State {
991            selected: usize,
992        }
993        impl Clone for State {
994            fn clone(&self) -> Self {
995                CLONES.fetch_add(1, Ordering::Relaxed);
996                Self {
997                    selected: self.selected,
998                }
999            }
1000        }
1001
1002        let state = Signal::new(State { selected: 0 });
1003        let selected = state.select(|state| state.selected);
1004        let (notifications, _subscription) = counter(&selected);
1005        state.modify(|state| {
1006            state.selected = 3;
1007            true
1008        });
1009        assert_eq!(selected.get(), 3);
1010        assert_eq!(notifications.load(Ordering::Relaxed), 1);
1011        assert_eq!(CLONES.load(Ordering::Relaxed), 0);
1012    }
1013
1014    #[test]
1015    fn selector_deduplicates_unrelated_source_changes() {
1016        #[derive(Clone, PartialEq)]
1017        struct State {
1018            selected: usize,
1019            detail: String,
1020        }
1021
1022        let state = Signal::new(State {
1023            selected: 0,
1024            detail: "first".to_string(),
1025        });
1026        let selected = state.select_named("selected", |state| state.selected);
1027        let (notifications, _subscription) = counter(&selected);
1028
1029        state.update(|state| state.detail = "second".to_string());
1030        assert_eq!(notifications.load(Ordering::Relaxed), 0);
1031        state.update(|state| state.selected = 1);
1032        assert_eq!(notifications.load(Ordering::Relaxed), 1);
1033        assert_eq!(selected.get(), 1);
1034    }
1035
1036    #[test]
1037    fn selector_observer_can_write_back_to_its_source() {
1038        let (done, completed) = std::sync::mpsc::channel();
1039        let worker = std::thread::spawn(move || {
1040            let source = Signal::new(0_u32);
1041            let selected = source.select(|value| *value);
1042            let writer = source.clone();
1043            let observed = Arc::new(Mutex::new(Vec::new()));
1044            let values = Arc::clone(&observed);
1045            let _subscription = selected.subscribe(Observer::new(move |_| {
1046                let value = writer.get();
1047                values.lock().unwrap().push(value);
1048                if value == 1 {
1049                    writer.set(2);
1050                }
1051            }));
1052            source.set(1);
1053            // An equal write must still be deduplicated after reentrant delivery.
1054            assert!(!source.set(2));
1055            done.send((source.get(), observed.lock().unwrap().clone()))
1056                .unwrap();
1057        });
1058        let (value, observed) = completed
1059            .recv_timeout(std::time::Duration::from_secs(5))
1060            .expect("selector source write-back deadlocked");
1061        worker.join().unwrap();
1062        assert_eq!(value, 2);
1063        assert_eq!(observed, vec![1, 2]);
1064    }
1065
1066    #[test]
1067    fn observers_run_on_the_writing_thread() {
1068        let signal = Signal::new(0_u32);
1069        let threads = Arc::new(Mutex::new(Vec::new()));
1070        let seen = Arc::clone(&threads);
1071        let _subscription = signal.subscribe(Observer::new(move |_| {
1072            seen.lock().unwrap().push(std::thread::current().id());
1073        }));
1074        let writer = signal.clone();
1075        let worker = std::thread::spawn(move || {
1076            writer.set(1);
1077            std::thread::current().id()
1078        })
1079        .join()
1080        .unwrap();
1081        signal.set(2);
1082        assert_eq!(
1083            *threads.lock().unwrap(),
1084            vec![worker, std::thread::current().id()]
1085        );
1086    }
1087
1088    fn counted_selector(
1089        source: &Signal<u32>,
1090    ) -> (Selector<Signal<u32>, u32, u32>, Arc<AtomicUsize>) {
1091        let runs = Arc::new(AtomicUsize::new(0));
1092        let counter = Arc::clone(&runs);
1093        let selector = source.select(move |value| {
1094            counter.fetch_add(1, Ordering::Relaxed);
1095            value % 3
1096        });
1097        (selector, runs)
1098    }
1099
1100    #[test]
1101    fn selector_runs_once_per_change_for_all_subscribers() {
1102        let source = Signal::new(0_u32);
1103        let (selected, runs) = counted_selector(&source);
1104        let subscriptions = (0..10)
1105            .map(|_| counter(&selected.clone()))
1106            .collect::<Vec<_>>();
1107        assert_eq!(runs.load(Ordering::Relaxed), 1, "seeded once");
1108
1109        source.set(1);
1110        assert_eq!(runs.load(Ordering::Relaxed), 2);
1111        for _ in 0..5 {
1112            assert_eq!(selected.get(), 1);
1113        }
1114        assert_eq!(
1115            runs.load(Ordering::Relaxed),
1116            2,
1117            "get reuses the cached value"
1118        );
1119        for (notifications, _) in &subscriptions {
1120            assert_eq!(notifications.load(Ordering::Relaxed), 1);
1121        }
1122
1123        source.set(4); // Same residue: recomputed once, nobody notified.
1124        assert_eq!(runs.load(Ordering::Relaxed), 3);
1125        assert_eq!(subscriptions[0].0.load(Ordering::Relaxed), 1);
1126    }
1127
1128    #[test]
1129    fn selector_releases_its_source_with_the_last_subscriber() {
1130        let source = Signal::new(0_u32);
1131        let (selected, runs) = counted_selector(&source);
1132        let first = counter(&selected);
1133        let second = counter(&selected);
1134        assert!(source.inner.core.has_observers());
1135
1136        drop(first);
1137        assert!(source.inner.core.has_observers(), "second still listening");
1138        drop(second);
1139        assert!(!source.inner.core.has_observers());
1140
1141        let before = runs.load(Ordering::Relaxed);
1142        source.set(1);
1143        assert_eq!(
1144            runs.load(Ordering::Relaxed),
1145            before,
1146            "no work while unobserved"
1147        );
1148        assert_eq!(selected.get(), 1);
1149
1150        let (notifications, _again) = counter(&selected);
1151        source.set(2);
1152        assert_eq!(notifications.load(Ordering::Relaxed), 1);
1153    }
1154
1155    #[test]
1156    fn chained_selectors_see_writes_made_inside_a_batch() {
1157        let source = Signal::new(1_u32);
1158        let doubled = source.select(|value| value * 2);
1159        let label = Selector::new("label", doubled.clone(), |value: &u32| format!("{value}"));
1160        let (_notifications, _subscription) = counter(&label);
1161        batch(|| {
1162            source.set(5);
1163            assert_eq!(label.get(), "10", "cache keyed by the source version");
1164        });
1165    }
1166
1167    /// A source that parks the notification reading `HELD` after it has
1168    /// derived a value but before the selector records it.
1169    #[derive(Clone)]
1170    struct GatedSource {
1171        signal: Signal<u32>,
1172        gate: Arc<(Mutex<(bool, bool)>, std::sync::Condvar)>,
1173    }
1174
1175    impl GatedSource {
1176        const HELD: u32 = 1;
1177
1178        fn wait(&self, until: impl Fn(&(bool, bool)) -> bool) {
1179            let (state, changed) = &*self.gate;
1180            let state = state.lock().unwrap();
1181            drop(changed.wait_while(state, |state| !until(state)).unwrap());
1182        }
1183
1184        fn update(&self, update: impl FnOnce(&mut (bool, bool))) {
1185            let (state, changed) = &*self.gate;
1186            update(&mut state.lock().unwrap());
1187            changed.notify_all();
1188        }
1189    }
1190
1191    impl Observable<u32> for GatedSource {
1192        fn source_id(&self) -> SourceId {
1193            self.signal.source_id()
1194        }
1195
1196        fn source_name(&self) -> Arc<str> {
1197            self.signal.source_name()
1198        }
1199
1200        fn get(&self) -> u32 {
1201            self.signal.get()
1202        }
1203
1204        fn read(&self, reader: &mut dyn FnMut(&u32)) {
1205            let value = self.signal.get();
1206            reader(&value);
1207            if value == Self::HELD {
1208                self.update(|(parked, _)| *parked = true);
1209                self.wait(|&(_, open)| open);
1210            }
1211        }
1212
1213        fn value_version(&self) -> Option<u64> {
1214            Some(self.signal.version())
1215        }
1216
1217        fn subscribe(&self, observer: Observer) -> Subscription {
1218            self.signal.subscribe(observer)
1219        }
1220    }
1221
1222    #[test]
1223    fn slow_notification_cannot_overwrite_a_newer_selection() {
1224        let signal = Signal::new(0_u32);
1225        let source = GatedSource {
1226            signal: signal.clone(),
1227            gate: Arc::new((Mutex::new((false, false)), std::sync::Condvar::new())),
1228        };
1229        let selected = Selector::new("residue", source.clone(), |value: &u32| value % 3);
1230        let (notifications, _subscription) = counter(&selected);
1231
1232        // A derives 1 from its write, then stalls before recording it.
1233        let slow = {
1234            let signal = signal.clone();
1235            std::thread::spawn(move || signal.set(GatedSource::HELD))
1236        };
1237        source.wait(|&(parked, _)| parked);
1238        // B writes 2 meanwhile. It either records 2 first or waits for A.
1239        let fast = {
1240            let signal = signal.clone();
1241            std::thread::spawn(move || signal.set(2))
1242        };
1243        std::thread::sleep(std::time::Duration::from_millis(50));
1244        source.update(|(_, open)| *open = true);
1245        slow.join().unwrap();
1246        fast.join().unwrap();
1247
1248        assert_eq!(lock(&selected.inner.tracking).delivered, Some(2));
1249        // A stale baseline of 1 would swallow this change.
1250        let before = notifications.load(Ordering::Relaxed);
1251        signal.set(4);
1252        assert_eq!(notifications.load(Ordering::Relaxed), before + 1);
1253    }
1254
1255    #[cfg(debug_assertions)]
1256    #[test]
1257    #[should_panic(expected = "signal `count` was written while this thread already holds")]
1258    fn writing_a_signal_inside_its_own_read_panics_in_debug() {
1259        let signal = Signal::named("count", 0_u32);
1260        signal.with(|_| signal.set(1));
1261    }
1262
1263    #[cfg(debug_assertions)]
1264    #[test]
1265    fn nested_reads_and_other_signals_are_allowed() {
1266        let first = Signal::new(1_u32);
1267        let second = Signal::new(2_u32);
1268        let sum = first.with(|a| first.with(|b| a + b) + second.with(|c| *c));
1269        assert_eq!(sum, 4);
1270        first.modify(|value| {
1271            second.set(*value);
1272            true
1273        });
1274        assert_eq!(second.get(), 1);
1275        // The lock record is cleared after a caught panic.
1276        let caught = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1277            first.with(|_| first.set(9));
1278        }));
1279        assert!(caught.is_err());
1280        assert!(first.set(3));
1281    }
1282
1283    #[test]
1284    fn mixed_concurrent_use_neither_deadlocks_nor_loses_the_final_value() {
1285        let (done, finished) = std::sync::mpsc::channel();
1286        std::thread::spawn(move || {
1287            let a = Signal::named("a", 0_u32);
1288            let b = Signal::named("b", 0_u32);
1289            let parity = a.select(|value| value % 2);
1290            let sum = combine((parity.clone(), b.clone()), |(parity, b)| parity + b);
1291            let task: Task<u32> = Task::new();
1292            let workers = (0..4_u32)
1293                .map(|thread| {
1294                    let (a, b, parity, sum, task) = (
1295                        a.clone(),
1296                        b.clone(),
1297                        parity.clone(),
1298                        sum.clone(),
1299                        task.clone(),
1300                    );
1301                    std::thread::spawn(move || {
1302                        for step in 0..300_u32 {
1303                            match (thread + step) % 5 {
1304                                0 => {
1305                                    a.set(step);
1306                                }
1307                                1 => batch(|| {
1308                                    a.update(|value| *value += 1);
1309                                    b.set(step % 7);
1310                                }),
1311                                2 => {
1312                                    // Subscription churn on shared selectors.
1313                                    let _parity = parity.subscribe(Observer::new(|_| {}));
1314                                    let _sum = sum.subscribe(Observer::new(|_| {}));
1315                                    let _ = sum.get();
1316                                }
1317                                3 => {
1318                                    let handle = task.refresh();
1319                                    handle.set_progress(0.5);
1320                                    handle.finish(step);
1321                                }
1322                                _ => {
1323                                    let _ = (parity.get(), sum.get(), task.progress());
1324                                }
1325                            }
1326                        }
1327                    })
1328                })
1329                .collect::<Vec<_>>();
1330            let latest = Arc::new(Mutex::new(None));
1331            let observed = Arc::clone(&latest);
1332            let reader = sum.clone();
1333            let _watch = sum.subscribe(Observer::new(move |_| {
1334                *observed.lock().unwrap() = Some(reader.get());
1335            }));
1336            for worker in workers {
1337                worker.join().unwrap();
1338            }
1339            // Quiescent: a final write must reach a live observer.
1340            a.set(1_001);
1341            b.set(41);
1342            let expected = 1 + 41;
1343            done.send((sum.get(), *latest.lock().unwrap(), expected))
1344                .unwrap();
1345        });
1346        let (sum, latest, expected) = finished
1347            .recv_timeout(std::time::Duration::from_secs(20))
1348            .expect("concurrent signal use deadlocked");
1349        assert_eq!(sum, expected);
1350        assert_eq!(latest, Some(expected));
1351    }
1352}