Skip to main content

cranpose_core/
state.rs

1use std::{
2    any::{Any, TypeId},
3    cell::{Cell, OnceCell, RefCell},
4    fmt,
5    hash::Hash,
6    marker::PhantomData,
7    ops::Deref,
8    rc::{Rc, Weak},
9};
10
11use smallvec::{SmallVec, smallvec};
12
13use crate::{
14    RuntimeHandle, ScopeId, StateId,
15    collections::map::HashMap,
16    runtime,
17    snapshot_id_set::{SnapshotId, SnapshotIdSet},
18    snapshot_v2::{
19        AnySnapshot, GlobalSnapshot, advance_global_snapshot, allocate_record_id, current_snapshot,
20    },
21};
22
23mod derived_state;
24mod readable_record;
25mod record_chain;
26mod snapshot_state_list;
27mod state_watchers;
28
29pub(crate) use derived_state::DerivedState;
30use readable_record::{ReadNotice, StateReadFailure, readable_record_for_active_snapshot};
31pub(crate) use record_chain::RecordChain;
32pub use snapshot_state_list::SnapshotStateList;
33use state_watchers::{StateWatchers, register_current_state_scope};
34
35pub(crate) const PREEXISTING_SNAPSHOT_ID: SnapshotId = SnapshotId(1);
36
37const INVALID_SNAPSHOT_ID: SnapshotId = SnapshotId(0);
38
39const SNAPSHOT_ID_MAX: SnapshotId = SnapshotId(usize::MAX);
40
41#[derive(Clone, Copy, Eq, PartialEq, Hash, Debug, Default)]
42pub struct ObjectId(pub(crate) usize);
43
44impl ObjectId {
45    #[cfg(test)]
46    pub(crate) fn new<T: ?Sized + 'static>(object: &Rc<T>) -> Self {
47        Self(Rc::as_ptr(object) as *const () as usize)
48    }
49}
50
51pub struct StateRecord {
52    snapshot_id: Cell<SnapshotId>,
53    tombstone: Cell<bool>,
54    value: RefCell<Option<Box<dyn RecordValue>>>,
55}
56
57pub(crate) trait RecordValue: Any {
58    fn clone_boxed(&self) -> Box<dyn RecordValue>;
59    fn assign_into(&self, target: &mut Option<Box<dyn RecordValue>>);
60    /// Whether dropping the value releases anything beyond its box.
61    fn holds_resources(&self) -> bool;
62}
63
64impl<T: Any + Clone> RecordValue for T {
65    fn holds_resources(&self) -> bool {
66        std::mem::needs_drop::<T>()
67    }
68
69    fn clone_boxed(&self) -> Box<dyn RecordValue> {
70        Box::new(self.clone())
71    }
72
73    fn assign_into(&self, target: &mut Option<Box<dyn RecordValue>>) {
74        match target
75            .as_mut()
76            .and_then(|value| (&mut **value as &mut dyn Any).downcast_mut::<T>())
77        {
78            Some(slot) => slot.clone_from(self),
79            None => *target = Some(Box::new(self.clone())),
80        }
81    }
82}
83
84#[derive(Debug, Clone, Copy, Eq, PartialEq)]
85pub(crate) enum StateRecordValueError {
86    Missing,
87}
88
89impl StateRecord {
90    pub(crate) fn new<T: Any + Clone>(snapshot_id: SnapshotId, value: T) -> Rc<Self> {
91        Self::with_boxed(snapshot_id, Box::new(value))
92    }
93
94    fn with_boxed(snapshot_id: SnapshotId, value: Box<dyn RecordValue>) -> Rc<Self> {
95        Rc::new(Self {
96            snapshot_id: Cell::new(snapshot_id),
97            tombstone: Cell::new(false),
98            value: RefCell::new(Some(value)),
99        })
100    }
101
102    #[inline]
103    pub(crate) fn snapshot_id(&self) -> SnapshotId {
104        self.snapshot_id.get()
105    }
106
107    #[inline]
108    pub(crate) fn set_snapshot_id(&self, id: SnapshotId) {
109        self.snapshot_id.set(id);
110    }
111
112    #[inline]
113    pub(crate) fn is_tombstone(&self) -> bool {
114        self.tombstone.get()
115    }
116
117    #[inline]
118    pub(crate) fn set_tombstone(&self, tombstone: bool) {
119        self.tombstone.set(tombstone);
120    }
121
122    /// Takes the value out of a record that no read reaches any more, for
123    /// the caller to drop once the operation that cleared it is done: its
124    /// destructor may read or write state. A value without drop glue holds
125    /// nothing to release and stays, so the record's next write stores over
126    /// it in place instead of boxing a new value.
127    #[must_use = "drop the cleared value once the record chain is consistent"]
128    pub(crate) fn clear_value(&self) -> Option<Box<dyn RecordValue>> {
129        let mut value = self.value.borrow_mut();
130        if value
131            .as_ref()
132            .is_some_and(|value| (**value).holds_resources())
133        {
134            value.take()
135        } else {
136            None
137        }
138    }
139
140    /// Marks the record dead and retires its value, for an operation that
141    /// holds a [`RetiredValuesScope`].
142    pub(crate) fn tombstone_retiring_value(&self) {
143        self.set_tombstone(true);
144        if let Some(value) = self.clear_value() {
145            retire_record_value(value);
146        }
147    }
148
149    /// Stores `new_value` and returns the value it displaced, for the caller
150    /// to drop once the write is published: its destructor may read or write
151    /// state.
152    #[must_use = "drop the displaced value once the write is published"]
153    pub(crate) fn replace_value<T: Any + Clone>(&self, new_value: T) -> Option<T> {
154        let mut value = self.value.borrow_mut();
155        if let Some(slot) = value
156            .as_mut()
157            .and_then(|current| (&mut **current as &mut dyn Any).downcast_mut::<T>())
158        {
159            return Some(std::mem::replace(slot, new_value));
160        }
161        let placeholder = value.replace(Box::new(new_value));
162        drop(value);
163        drop(placeholder);
164        None
165    }
166
167    fn cloned_value(&self) -> Option<Box<dyn RecordValue>> {
168        self.value
169            .borrow()
170            .as_ref()
171            .map(|value| (**value).clone_boxed())
172    }
173
174    fn cloned_value_of(&self, expected: TypeId) -> Option<Box<dyn RecordValue>> {
175        self.value
176            .borrow()
177            .as_ref()
178            .filter(|value| (&***value as &dyn Any).type_id() == expected)
179            .map(|value| (**value).clone_boxed())
180    }
181
182    fn set_boxed_value(&self, value: Box<dyn RecordValue>) {
183        let displaced = self.value.borrow_mut().replace(value);
184        if let Some(displaced) = displaced {
185            retire_record_value(displaced);
186        }
187    }
188
189    pub(crate) fn with_value<T: Any, R>(&self, f: impl FnOnce(&T) -> R) -> R {
190        self.try_with_value(f)
191            .unwrap_or_else(|| panic!("StateRecord value missing or wrong type"))
192    }
193
194    pub(crate) fn try_with_value<T: Any, R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
195        let guard = self.value.borrow();
196        let value = guard
197            .as_ref()
198            .and_then(|boxed| (&**boxed as &dyn Any).downcast_ref::<T>())?;
199        Some(f(value))
200    }
201
202    #[cfg(test)]
203    pub(crate) fn clear_for_reuse(&self) {
204        drop(self.value.borrow_mut().take());
205    }
206
207    pub(crate) fn assign_value(&self, source: &Self) -> Result<(), StateRecordValueError> {
208        if std::ptr::eq(self, source) {
209            return match self.value.borrow().is_some() {
210                true => Ok(()),
211                false => Err(StateRecordValueError::Missing),
212            };
213        }
214        let source_value = source.value.borrow();
215        let value = source_value
216            .as_ref()
217            .ok_or(StateRecordValueError::Missing)?;
218        (**value).assign_into(&mut self.value.borrow_mut());
219        Ok(())
220    }
221}
222
223#[cold]
224fn log_merge_value_missing(which: &str, state: ObjectId, record: &StateRecord) {
225    log::error!(
226        "SnapshotMutableState::merge_records {which} record value missing or wrong type (state {state:?}, {which}_id={})",
227        record.snapshot_id()
228    );
229}
230
231fn install_copy_as_head(
232    state: &dyn StateObject,
233    source: &StateRecord,
234    expected: TypeId,
235) -> Option<SnapshotId> {
236    let value = source.cloned_value_of(expected)?;
237    let new_id = allocate_record_id();
238    let record = state.records().overwritable_head();
239    record.set_boxed_value(value);
240    record.set_tombstone(false);
241    record.set_snapshot_id(new_id);
242    advance_global_snapshot(new_id);
243    Some(new_id)
244}
245
246fn promote_record_locked(
247    state: &dyn StateObject,
248    child_id: SnapshotId,
249    expected: TypeId,
250) -> Result<(), &'static str> {
251    let Some(record) = state.records().at(child_id) else {
252        log::error!(
253            "SnapshotMutableState::promote_record missing child record (state {:?}, child_id={})",
254            state.object_id(),
255            child_id
256        );
257        return Err("missing child record");
258    };
259    if install_copy_as_head(state, &record, expected).is_none() {
260        log::error!(
261            "SnapshotMutableState::promote_record child record value missing or wrong type (state {:?}, child_id={})",
262            state.object_id(),
263            child_id
264        );
265        return Err("child record value missing or wrong type");
266    }
267    Ok(())
268}
269
270fn commit_merged_record_locked(
271    state: &dyn StateObject,
272    merged: &StateRecord,
273    expected: TypeId,
274) -> Result<SnapshotId, &'static str> {
275    install_copy_as_head(state, merged, expected).ok_or_else(|| {
276        log::error!(
277            "SnapshotMutableState::commit_merged_record merged record value missing or wrong type (state {:?}, merged_id={})",
278            state.object_id(),
279            merged.snapshot_id()
280        );
281        "merged record value missing or wrong type"
282    })
283}
284
285/// Drops `value`, a record value displaced inside snapshot bookkeeping, once
286/// the outermost [`RetiredValuesScope`] ends, or now when none is open: its
287/// destructor may read or write state.
288pub(crate) fn retire_record_value(value: Box<dyn RecordValue>) {
289    let held = crate::thread_state::try_snapshots(|state| {
290        if state.retire_depth.get() == 0 {
291            return Some(value);
292        }
293        state.retired_record_values.borrow_mut().push(value);
294        None
295    });
296    drop(held);
297}
298
299/// Holds back the drop of retired record values until the outermost scope
300/// ends, so no destructor runs while snapshot bookkeeping is half done.
301pub(crate) struct RetiredValuesScope(());
302
303impl RetiredValuesScope {
304    pub(crate) fn enter() -> Self {
305        crate::thread_state::snapshots(|state| {
306            state.retire_depth.set(state.retire_depth.get() + 1);
307        });
308        Self(())
309    }
310}
311
312impl Drop for RetiredValuesScope {
313    fn drop(&mut self) {
314        let retired = crate::thread_state::snapshots(|state| {
315            let depth = state.retire_depth.get() - 1;
316            state.retire_depth.set(depth);
317            (depth == 0).then(|| state.retired_record_values.take())
318        });
319        drop(retired);
320    }
321}
322
323fn active_snapshot() -> AnySnapshot {
324    current_snapshot().unwrap_or_else(|| AnySnapshot::Global(GlobalSnapshot::get_or_create()))
325}
326
327pub(crate) trait MutationPolicy<T>: Send + Sync {
328    fn equivalent(&self, a: &T, b: &T) -> bool;
329    fn merge(&self, _previous: &T, _current: &T, _applied: &T) -> Option<T> {
330        None
331    }
332}
333
334pub(crate) struct NeverEqual;
335
336impl<T> MutationPolicy<T> for NeverEqual {
337    fn equivalent(&self, _a: &T, _b: &T) -> bool {
338        false
339    }
340}
341
342pub(crate) struct StructuralEqual;
343
344impl<T: PartialEq> MutationPolicy<T> for StructuralEqual {
345    fn equivalent(&self, a: &T, b: &T) -> bool {
346        a == b
347    }
348}
349
350pub trait StateObject: Any {
351    fn object_id(&self) -> ObjectId;
352    fn records(&self) -> &RecordChain;
353    fn try_readable_record(
354        &self,
355        snapshot_id: SnapshotId,
356        invalid: &SnapshotIdSet,
357    ) -> Option<Rc<StateRecord>>;
358    fn readable_record(&self, snapshot_id: SnapshotId, invalid: &SnapshotIdSet) -> Rc<StateRecord>;
359
360    fn merge_records(
361        &self,
362        _previous: Rc<StateRecord>,
363        _current: Rc<StateRecord>,
364        _applied: Rc<StateRecord>,
365    ) -> Option<Rc<StateRecord>> {
366        None
367    }
368
369    fn commit_merged_record(&self, _merged: Rc<StateRecord>) -> Result<SnapshotId, &'static str> {
370        Err("StateObject does not support merged record commits")
371    }
372    fn promote_record(&self, child_id: SnapshotId) -> Result<(), &'static str>;
373
374    fn overwrite_unused_records(&self) -> bool {
375        false
376    }
377
378    fn observation_lease(&self) -> Option<Rc<dyn Any>> {
379        None
380    }
381
382    fn as_any(&self) -> &dyn Any;
383}
384
385pub(crate) struct SnapshotMutableState<T> {
386    records: RecordChain,
387    policy: Rc<dyn MutationPolicy<T>>,
388    id: ObjectId,
389    weak_self: Weak<Self>,
390    apply_observer: ApplyObserver,
391    subscribers: Subscribers,
392}
393
394// Who subscribes to a state, whatever its value's type: the leases on its
395// reads, the scopes that observe it and the callbacks to run when it gains
396// its first subscriber. Kept apart from the value's type, so its code is
397// compiled once for every state type.
398#[derive(Default)]
399pub(crate) struct Subscribers {
400    lease: Rc<()>,
401    scopes: Cell<usize>,
402    callbacks: RefCell<Vec<Rc<dyn Fn()>>>,
403}
404
405impl Subscribers {
406    fn acquire_observation_lease(&self) -> Option<Rc<dyn Any>> {
407        let was_empty = !self.has_subscribers();
408        let lease = Rc::clone(&self.lease);
409        if was_empty {
410            notify_subscriber_callbacks(&self.callbacks);
411        }
412        Some(lease)
413    }
414
415    fn add_scope_observer(&self) -> bool {
416        let was_empty = !self.has_subscribers();
417        let count = self
418            .scopes
419            .get()
420            .checked_add(1)
421            .expect("state scope observation count overflow");
422        self.scopes.set(count);
423        was_empty
424    }
425
426    fn remove_scope_observers(&self, count: usize) {
427        if count == 0 {
428            return;
429        }
430        let remaining = self
431            .scopes
432            .get()
433            .checked_sub(count)
434            .expect("state scope observation count underflow");
435        self.scopes.set(remaining);
436    }
437
438    fn has_subscribers(&self) -> bool {
439        Rc::strong_count(&self.lease) > 1 || self.scopes.get() > 0
440    }
441
442    fn subscriber_callback(&self, callback: Rc<dyn Fn()>, notify: bool) {
443        self.callbacks.borrow_mut().push(Rc::clone(&callback));
444        if notify {
445            callback();
446        }
447    }
448
449    fn notify_subscribers(&self) {
450        notify_subscriber_callbacks(&self.callbacks);
451    }
452}
453
454#[inline(always)]
455fn assert_record_chain(
456    records: &RecordChain,
457    id: ObjectId,
458    caller: &str,
459    snapshot_context: Option<SnapshotId>,
460) {
461    if should_check_chain_integrity() {
462        records.check_integrity(id, caller, snapshot_context);
463    }
464}
465
466enum Merge<'a, T> {
467    KeepCurrent,
468    Value(Option<T>),
469    Missing(&'static str, &'a Rc<StateRecord>),
470}
471
472type ApplyObserver = OnceCell<Box<dyn Fn() + 'static>>;
473
474fn notify_applied(observer: &ApplyObserver) {
475    if let Some(observer) = observer.get() {
476        observer();
477    }
478}
479
480fn finish_apply(
481    observer: &ApplyObserver,
482    records: &RecordChain,
483    id: ObjectId,
484    caller: &str,
485    snapshot_id: SnapshotId,
486) {
487    notify_applied(observer);
488    assert_record_chain(records, id, caller, Some(snapshot_id));
489}
490
491// What a write does that does not depend on the state's value type, so it
492// is compiled once instead of once per state type.
493struct WriteTarget<'a> {
494    records: &'a RecordChain,
495    id: ObjectId,
496}
497
498impl WriteTarget<'_> {
499    fn assert_chain_integrity(&self, caller: &str, snapshot_context: Option<SnapshotId>) {
500        assert_record_chain(self.records, self.id, caller, snapshot_context);
501    }
502
503    fn begin_global_write(&self, global: &GlobalSnapshot, snapshot_id: SnapshotId) {
504        assert!(
505            !global.has_pending_children(),
506            "SnapshotMutableState::set attempted global write while pending children {:?} exist (state {:?}, snapshot_id={})",
507            global.pending_children(),
508            self.id,
509            snapshot_id
510        );
511        mark_update_write(self.id);
512    }
513
514    /// Returns a head record for a global write and the id under which
515    /// [`Self::publish_global_record`] publishes it.
516    fn push_global_record(&self) -> (Rc<StateRecord>, SnapshotId) {
517        let new_id = allocate_record_id();
518        (self.records.overwritable_head(), new_id)
519    }
520
521    /// Publishes a pushed record once its value is stored: nothing may read
522    /// the record while the store runs.
523    fn publish_global_record(
524        &self,
525        record: &StateRecord,
526        new_id: SnapshotId,
527        snapshot_id: SnapshotId,
528    ) {
529        record.set_snapshot_id(new_id);
530        record.set_tombstone(false);
531        advance_global_snapshot(new_id);
532        self.assert_chain_integrity("set(global-push)", Some(snapshot_id));
533    }
534
535    /// Finishes a global write that stored its value in `record`, the record
536    /// at the global snapshot's current id.
537    fn finish_global_write(
538        &self,
539        record: &StateRecord,
540        written: Option<Rc<dyn StateObject>>,
541        snapshot_id: SnapshotId,
542    ) {
543        let mut cleared: SmallVec<[Box<dyn RecordValue>; 2]> = SmallVec::new();
544        self.records.clear_hidden_after(record, &mut cleared);
545        self.assert_chain_integrity("set(global-tombstone)", Some(snapshot_id));
546        if let Some(modified) = written.as_ref() {
547            crate::snapshot_v2::notify_apply_observers(
548                std::slice::from_ref(modified),
549                record.snapshot_id(),
550            );
551        }
552        drop(cleared);
553    }
554
555    fn begin_child_write(
556        &self,
557        snapshot: &AnySnapshot,
558        snapshot_id: SnapshotId,
559        invalid: &SnapshotIdSet,
560        written: Option<Rc<dyn StateObject>>,
561    ) -> Rc<StateRecord> {
562        if let Some(state) = written {
563            snapshot.record_write(state);
564        }
565        mark_update_write(self.id);
566        self.writable_record(snapshot_id, invalid)
567    }
568
569    fn writable_record(&self, snapshot_id: SnapshotId, invalid: &SnapshotIdSet) -> Rc<StateRecord> {
570        let Some(readable) = self.records.readable(snapshot_id, invalid) else {
571            let cloned_value = self
572                .records
573                .head()
574                .cloned_value()
575                .unwrap_or_else(|| panic!("StateRecord value missing or wrong type"));
576            let new_head = StateRecord::with_boxed(snapshot_id, cloned_value);
577            self.records.prepend(Rc::clone(&new_head));
578            self.assert_chain_integrity("writable_record(recover)", Some(snapshot_id));
579            return new_head;
580        };
581
582        if readable.snapshot_id() == snapshot_id {
583            return readable;
584        }
585
586        let overwritable = self.records.overwritable();
587        if let Err(error) = overwritable.assign_value(&readable) {
588            log::error!(
589                "snapshot writable record could not copy the readable value for state {:?}: {:?}",
590                self.id,
591                error
592            );
593        }
594        overwritable.set_snapshot_id(snapshot_id);
595        overwritable.set_tombstone(false);
596
597        self.assert_chain_integrity("writable_record(reuse)", Some(snapshot_id));
598
599        overwritable
600    }
601}
602
603// The steps of a write that depend on the state's value type; `write_value`
604// takes the rest, compiled once for every state type.
605trait PendingWrite {
606    // Whether `record` holds a value the state's policy deems the new one.
607    fn matches(&self, record: &StateRecord) -> bool;
608    // Moves the new value into `record` and keeps the value it displaced, to
609    // drop once the write is published.
610    fn store(&mut self, record: &StateRecord);
611    // The state written, for the snapshots to report.
612    fn written(&self) -> Option<Rc<dyn StateObject>>;
613}
614
615struct TypedWrite<'a, T> {
616    state: &'a SnapshotMutableState<T>,
617    value: Option<T>,
618    displaced: Option<T>,
619}
620
621impl<T: Clone + 'static> PendingWrite for TypedWrite<'_, T> {
622    fn matches(&self, record: &StateRecord) -> bool {
623        self.value.as_ref().is_some_and(|value| {
624            record.with_value(|current: &T| self.state.policy.equivalent(current, value))
625        })
626    }
627
628    fn store(&mut self, record: &StateRecord) {
629        if let Some(value) = self.value.take() {
630            self.displaced = record.replace_value(value);
631        }
632    }
633
634    fn written(&self) -> Option<Rc<dyn StateObject>> {
635        self.state.written_state()
636    }
637}
638
639// Writes the value `write` holds to the state `target` names, in the active
640// snapshot, and returns whether it changed the value that snapshot reads.
641// Out of line, one function for every state type.
642#[inline(never)]
643fn write_value(target: &WriteTarget<'_>, write: &mut dyn PendingWrite) -> bool {
644    #[cfg(debug_assertions)]
645    {
646        let in_handler = crate::in_event_handler();
647        let in_snapshot = crate::in_applied_snapshot();
648        if in_handler && !in_snapshot {
649            log::warn!(
650                target: "cranpose::state",
651                "State modified in event handler without run_in_mutable_snapshot; \
652                 this can make updates invisible to other contexts. Wrap the handler \
653                 in run_in_mutable_snapshot() or dispatch_ui_event(). State: {:?}",
654                target.id
655            );
656        }
657    }
658
659    let snapshot = active_snapshot();
660    let snapshot_id = snapshot.snapshot_id();
661    let readable_for =
662        |snapshot_id, invalid: &SnapshotIdSet| target.records.readable(snapshot_id, invalid);
663
664    match &snapshot {
665        AnySnapshot::Global(global) => {
666            let readable = snapshot.with_invalid(|invalid| readable_for(snapshot_id, invalid));
667            if readable
668                .as_deref()
669                .is_some_and(|record| write.matches(record))
670            {
671                return false;
672            }
673            target.begin_global_write(global, snapshot_id);
674            // A record the global snapshot wrote at its current id is
675            // seen by no other snapshot: one taken since would have moved
676            // the global to a new id. The write replaces its value there,
677            // as Compose overwrites the record of the snapshot it writes.
678            if let Some(record) = readable.filter(|record| record.snapshot_id() == snapshot_id) {
679                write.store(&record);
680                target.finish_global_write(&record, write.written(), snapshot_id);
681            } else {
682                let (record, new_id) = target.push_global_record();
683                write.store(&record);
684                target.publish_global_record(&record, new_id, snapshot_id);
685                target.finish_global_write(&record, write.written(), snapshot_id);
686            }
687        }
688        AnySnapshot::Mutable(_)
689        | AnySnapshot::NestedMutable(_)
690        | AnySnapshot::TransparentMutable(_) => {
691            let invalid = snapshot.invalid();
692            if readable_for(snapshot_id, &invalid)
693                .as_deref()
694                .is_some_and(|record| write.matches(record))
695            {
696                return false;
697            }
698            let record =
699                target.begin_child_write(&snapshot, snapshot_id, &invalid, write.written());
700            write.store(&record);
701            target.assert_chain_integrity("set(child-writable)", Some(snapshot_id));
702        }
703        AnySnapshot::Readonly(_)
704        | AnySnapshot::NestedReadonly(_)
705        | AnySnapshot::TransparentReadonly(_) => {
706            panic!("Cannot write to a read-only snapshot");
707        }
708    }
709
710    true
711}
712
713fn should_check_chain_integrity() -> bool {
714    #[cfg(debug_assertions)]
715    {
716        true
717    }
718
719    #[cfg(not(debug_assertions))]
720    {
721        crate::DIAGNOSTICS.assert_state_chain.is_set()
722    }
723}
724
725impl<T: Clone + 'static> SnapshotMutableState<T> {
726    fn readable_record_for_active_snapshot(&self) -> Result<Rc<StateRecord>, StateReadFailure> {
727        readable_record_for_active_snapshot(ReadNotice::Observers(self), &self.records, self.id)
728    }
729
730    fn readable_for(
731        &self,
732        snapshot_id: SnapshotId,
733        invalid: &SnapshotIdSet,
734    ) -> Option<Rc<StateRecord>> {
735        self.records.readable(snapshot_id, invalid)
736    }
737
738    pub(crate) fn new_in_rc(initial: T, policy: Rc<dyn MutationPolicy<T>>) -> Rc<Self> {
739        let snapshot = active_snapshot();
740        let snapshot_id = snapshot.snapshot_id();
741
742        let tail = StateRecord::new(PREEXISTING_SNAPSHOT_ID, initial.clone());
743        let head = StateRecord::new(snapshot_id, initial);
744
745        Rc::new_cyclic(|weak_self| Self {
746            records: RecordChain::new(smallvec![head, tail]),
747            policy,
748            id: ObjectId(weak_self.as_ptr() as usize),
749            weak_self: Weak::clone(weak_self),
750            apply_observer: OnceCell::new(),
751            subscribers: Subscribers::default(),
752        })
753    }
754
755    pub(crate) fn set_apply_observer(&self, observer: Box<dyn Fn() + 'static>) {
756        assert!(
757            self.apply_observer.set(observer).is_ok(),
758            "state observer already installed"
759        );
760    }
761
762    fn finish_apply(&self, caller: &str, snapshot_id: SnapshotId) {
763        finish_apply(
764            &self.apply_observer,
765            &self.records,
766            self.id,
767            caller,
768            snapshot_id,
769        );
770    }
771
772    fn upgrade_self(&self) -> Option<Rc<Self>> {
773        self.weak_self.upgrade()
774    }
775
776    fn written_state(&self) -> Option<Rc<dyn StateObject>> {
777        self.upgrade_self()
778            .map(|state| -> Rc<dyn StateObject> { state })
779    }
780
781    #[inline]
782    pub(crate) fn id(&self) -> ObjectId {
783        self.id
784    }
785
786    pub(crate) fn try_with_value<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
787        let record = self.readable_record_for_active_snapshot().ok()?;
788        record.try_with_value(f)
789    }
790
791    pub(crate) fn try_get(&self) -> Option<T> {
792        self.try_with_value(Clone::clone)
793    }
794
795    pub(crate) fn with_value<R>(&self, f: impl FnOnce(&T) -> R) -> R {
796        let record = self
797            .readable_record_for_active_snapshot()
798            .unwrap_or_else(|failure| panic!("{failure}"));
799        record.with_value(f)
800    }
801
802    pub(crate) fn get(&self) -> T {
803        self.with_value(Clone::clone)
804    }
805
806    pub(crate) fn set(&self, new_value: T) -> bool {
807        let target = WriteTarget {
808            records: &self.records,
809            id: self.id,
810        };
811        let mut write = TypedWrite {
812            state: self,
813            value: Some(new_value),
814            displaced: None,
815        };
816        // The value the write displaced drops with `write`, once the write
817        // is published.
818        write_value(&target, &mut write)
819    }
820
821    fn try_readable_record(
822        &self,
823        snapshot_id: SnapshotId,
824        invalid: &SnapshotIdSet,
825    ) -> Option<Rc<StateRecord>> {
826        self.readable_for(snapshot_id, invalid)
827    }
828}
829
830pub(crate) struct UpdateScope {
831    id: ObjectId,
832    finished: bool,
833}
834
835impl UpdateScope {
836    pub(crate) fn new(id: ObjectId) -> Self {
837        crate::thread_state::snapshots(|state| {
838            state.active_updates.borrow_mut().insert(id);
839            state.pending_writes.borrow_mut().remove(&id);
840        });
841        Self {
842            id,
843            finished: false,
844        }
845    }
846
847    pub(crate) fn finish(mut self) -> bool {
848        self.finished = true;
849        crate::thread_state::snapshots(|state| {
850            state.active_updates.borrow_mut().remove(&self.id);
851            state.pending_writes.borrow_mut().remove(&self.id)
852        })
853    }
854}
855
856impl Drop for UpdateScope {
857    fn drop(&mut self) {
858        if self.finished {
859            return;
860        }
861        crate::thread_state::snapshots(|state| {
862            state.active_updates.borrow_mut().remove(&self.id);
863            state.pending_writes.borrow_mut().remove(&self.id);
864        });
865    }
866}
867
868fn mark_update_write(id: ObjectId) {
869    crate::thread_state::snapshots(|state| {
870        if state.active_updates.borrow().contains(&id) {
871            state.pending_writes.borrow_mut().insert(id);
872        }
873    });
874}
875
876impl<T: Clone + 'static> StateObject for SnapshotMutableState<T> {
877    fn object_id(&self) -> ObjectId {
878        self.id
879    }
880
881    fn records(&self) -> &RecordChain {
882        &self.records
883    }
884
885    fn try_readable_record(
886        &self,
887        snapshot_id: SnapshotId,
888        invalid: &SnapshotIdSet,
889    ) -> Option<Rc<StateRecord>> {
890        self.try_readable_record(snapshot_id, invalid)
891    }
892
893    fn readable_record(&self, snapshot_id: SnapshotId, invalid: &SnapshotIdSet) -> Rc<StateRecord> {
894        self.try_readable_record(snapshot_id, invalid)
895            .unwrap_or_else(|| {
896                panic!(
897                    "SnapshotMutableState::readable_record returned null (state={:?}, snapshot_id={})",
898                    self.id, snapshot_id
899                )
900            })
901    }
902
903    fn observation_lease(&self) -> Option<Rc<dyn Any>> {
904        self.subscribers.acquire_observation_lease()
905    }
906
907    fn merge_records(
908        &self,
909        previous: Rc<StateRecord>,
910        current: Rc<StateRecord>,
911        applied: Rc<StateRecord>,
912    ) -> Option<Rc<StateRecord>> {
913        let outcome = current
914            .try_with_value(|current_value: &T| {
915                applied
916                    .try_with_value(|applied_value: &T| {
917                        if self.policy.equivalent(current_value, applied_value) {
918                            return Merge::KeepCurrent;
919                        }
920                        previous
921                            .try_with_value(|previous_value: &T| {
922                                Merge::Value(self.policy.merge(
923                                    previous_value,
924                                    current_value,
925                                    applied_value,
926                                ))
927                            })
928                            .unwrap_or(Merge::Missing("previous", &previous))
929                    })
930                    .unwrap_or(Merge::Missing("applied", &applied))
931            })
932            .unwrap_or(Merge::Missing("current", &current));
933        match outcome {
934            Merge::KeepCurrent => Some(current),
935            Merge::Value(merged) => {
936                merged.map(|value| StateRecord::new(applied.snapshot_id(), value))
937            }
938            Merge::Missing(which, record) => {
939                log_merge_value_missing(which, self.id, record);
940                None
941            }
942        }
943    }
944
945    fn promote_record(&self, child_id: SnapshotId) -> Result<(), &'static str> {
946        promote_record_locked(self, child_id, TypeId::of::<T>())?;
947        self.finish_apply("promote_record", child_id);
948        Ok(())
949    }
950
951    fn commit_merged_record(&self, merged: Rc<StateRecord>) -> Result<SnapshotId, &'static str> {
952        let new_id = commit_merged_record_locked(self, &merged, TypeId::of::<T>())?;
953        self.finish_apply("commit_merged_record", new_id);
954        Ok(new_id)
955    }
956
957    fn overwrite_unused_records(&self) -> bool {
958        self.records.overwrite_unused()
959    }
960
961    fn as_any(&self) -> &dyn Any {
962        self
963    }
964}
965
966pub(crate) struct MutableStateInner<T: Clone + 'static> {
967    pub(crate) state: Rc<SnapshotMutableState<T>>,
968    watchers: StateWatchers,
969}
970
971fn notify_subscriber_callbacks(callbacks: &RefCell<Vec<Rc<dyn Fn()>>>) {
972    let registered = callbacks.borrow().len();
973    for index in 0..registered {
974        let callback = callbacks.borrow().get(index).map(Rc::clone);
975        if let Some(callback) = callback {
976            callback();
977        }
978    }
979}
980
981// What a state's apply observer runs: invalidates the scopes that read the
982// state, on the UI thread. The arena finds the readers by the state's id, so
983// the closure is one function for every state type.
984fn watcher_invalidation(runtime: RuntimeHandle, state_id: StateId) -> Box<dyn Fn()> {
985    Box::new(move || {
986        let ui_runtime = runtime.clone();
987        runtime.enqueue_ui_task(Box::new(move || {
988            ui_runtime.with_state_arena(|arena| arena.invalidate_watchers(state_id));
989        }));
990    })
991}
992
993impl<T: Clone + 'static> MutableStateInner<T> {
994    pub(crate) fn new_with_policy(
995        value: T,
996        runtime: RuntimeHandle,
997        policy: Rc<dyn MutationPolicy<T>>,
998    ) -> Self {
999        Self {
1000            state: SnapshotMutableState::new_in_rc(value, policy),
1001            watchers: StateWatchers {
1002                scopes: RefCell::new(HashMap::default()),
1003                runtime,
1004                state_id: Cell::new(None),
1005            },
1006        }
1007    }
1008
1009    pub(crate) fn install_snapshot_observer(&self, state_id: StateId) {
1010        self.watchers.state_id.set(Some(state_id));
1011        self.state.set_apply_observer(watcher_invalidation(
1012            self.watchers.runtime.clone(),
1013            state_id,
1014        ));
1015    }
1016
1017    fn has_subscribers(&self) -> bool {
1018        self.watchers.has_subscribers(&self.state.subscribers)
1019    }
1020
1021    /// Removes the live scope `scope_id` from the watchers: its last body did
1022    /// not read the state.
1023    pub(crate) fn forget_scope(&self, scope_id: ScopeId) {
1024        self.watchers
1025            .forget_scope(&self.state.subscribers, scope_id);
1026    }
1027
1028    pub(crate) fn unregister_scope(&self, scope_id: ScopeId) {
1029        self.watchers
1030            .unregister_scope(&self.state.subscribers, scope_id);
1031    }
1032
1033    pub(crate) fn invalidate_watchers(&self) {
1034        self.watchers
1035            .invalidate(&self.state.subscribers, std::any::type_name::<T>());
1036    }
1037
1038    // Subscribes the scope that is composing to this state.
1039    fn register_current_scope(&self) {
1040        register_current_state_scope(&self.watchers, &self.state.subscribers);
1041    }
1042}
1043
1044impl<T: Clone + 'static> Drop for MutableStateInner<T> {
1045    fn drop(&mut self) {
1046        self.state
1047            .subscribers
1048            .remove_scope_observers(self.watchers.scopes.get_mut().len());
1049    }
1050}
1051
1052trait StateArenaHandle<T: Clone + 'static> {
1053    fn state_id(&self) -> StateId;
1054    fn runtime_id(&self) -> runtime::RuntimeId;
1055
1056    fn runtime_handle(&self) -> RuntimeHandle {
1057        runtime::runtime_handle_by_id(self.runtime_id())
1058            .unwrap_or_else(|| panic!("runtime {:?} dropped", self.runtime_id()))
1059    }
1060
1061    fn runtime_handle_opt(&self) -> Option<RuntimeHandle> {
1062        runtime::runtime_handle_by_id(self.runtime_id())
1063    }
1064
1065    fn with_inner<R>(&self, f: impl FnOnce(&MutableStateInner<T>) -> R) -> R {
1066        runtime::with_state_arena_by_id(self.runtime_id(), |arena| {
1067            arena.with_typed::<T, R>(self.state_id(), f)
1068        })
1069        .unwrap_or_else(|| panic!("runtime {:?} dropped", self.runtime_id()))
1070    }
1071
1072    fn try_with_inner<R>(&self, f: impl FnOnce(&MutableStateInner<T>) -> R) -> Option<R> {
1073        runtime::with_state_arena_by_id(self.runtime_id(), |arena| {
1074            arena.with_typed_opt::<T, R>(self.state_id(), f)
1075        })?
1076    }
1077
1078    fn read_subscribed<R>(&self, read: impl FnOnce(&MutableStateInner<T>) -> R) -> R {
1079        self.with_inner(|inner| {
1080            let result = read(inner);
1081            inner.register_current_scope();
1082            result
1083        })
1084    }
1085}
1086
1087/// Cheap copyable read-only view of a state cell.
1088pub struct State<T: Clone + 'static> {
1089    id: StateId,
1090    runtime_id: runtime::RuntimeId,
1091    /// The cell holds a derived state's value, which a read brings up to
1092    /// date first.
1093    derived: bool,
1094    _marker: PhantomData<fn() -> T>,
1095}
1096
1097/// Cheap copyable mutable view of a state cell.
1098///
1099/// Ownership lives elsewhere: a composition slot, an [`OwnedMutableState`], or
1100/// the runtime for states created with [`crate::mutableStateOf`] /
1101/// [`MutableState::with_runtime`].
1102pub struct MutableState<T: Clone + 'static> {
1103    id: StateId,
1104    runtime_id: runtime::RuntimeId,
1105    _marker: PhantomData<fn() -> T>,
1106}
1107
1108/// Owning state handle for reclaimable state cells.
1109#[derive(Clone)]
1110pub struct OwnedMutableState<T: Clone + 'static> {
1111    state: MutableState<T>,
1112    _lease: Rc<runtime::StateHandleLease>,
1113    _marker: PhantomData<fn() -> T>,
1114}
1115
1116impl<T: Clone + 'static> PartialEq for State<T> {
1117    fn eq(&self, other: &Self) -> bool {
1118        self.state_id() == other.state_id() && self.runtime_id() == other.runtime_id()
1119    }
1120}
1121
1122impl<T: Clone + 'static> Eq for State<T> {}
1123
1124impl<T: Clone + 'static> PartialEq for MutableState<T> {
1125    fn eq(&self, other: &Self) -> bool {
1126        self.state_id() == other.state_id() && self.runtime_id() == other.runtime_id()
1127    }
1128}
1129
1130/// Two owning handles are equal when they hold the same state, as two
1131/// [`MutableState`] handles are.
1132impl<T: Clone + 'static> PartialEq for OwnedMutableState<T> {
1133    fn eq(&self, other: &Self) -> bool {
1134        self.state == other.state
1135    }
1136}
1137
1138impl<T: Clone + 'static> Eq for MutableState<T> {}
1139
1140impl<T: Clone + 'static> Copy for State<T> {}
1141
1142impl<T: Clone + 'static> Clone for State<T> {
1143    fn clone(&self) -> Self {
1144        *self
1145    }
1146}
1147
1148impl<T: Clone + 'static> Copy for MutableState<T> {}
1149
1150impl<T: Clone + 'static> Clone for MutableState<T> {
1151    fn clone(&self) -> Self {
1152        *self
1153    }
1154}
1155
1156impl<T: Clone + 'static> StateArenaHandle<T> for State<T> {
1157    fn state_id(&self) -> StateId {
1158        self.id
1159    }
1160
1161    fn runtime_id(&self) -> runtime::RuntimeId {
1162        self.runtime_id
1163    }
1164}
1165
1166impl<T: Clone + 'static> State<T> {
1167    /// Returns `true` while the state exists. It ends when its owner releases it or its runtime is
1168    /// dropped.
1169    pub fn is_alive(&self) -> bool {
1170        self.try_with_inner(|_| ()).is_some()
1171    }
1172
1173    /// Reads the value through `f` without subscribing the current scope. Returns `None` if the
1174    /// state was released or has no readable value.
1175    pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
1176        self.try_with_fresh_inner(|inner| inner.state.try_with_value(f))?
1177    }
1178
1179    /// Returns a copy of the value without subscribing the current scope, or `None` if the state
1180    /// was released or has no readable value.
1181    pub fn try_value(&self) -> Option<T> {
1182        self.try_with_fresh_inner(|inner| inner.state.try_get())?
1183    }
1184
1185    /// Reads a copy of the value through `f` and subscribes the current
1186    /// scope. `f` may write this state; see [`Self::read`] for a read that
1187    /// borrows instead of copying.
1188    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1189        let value = self.read_fresh_subscribed(|inner| inner.state.get());
1190        f(&value)
1191    }
1192
1193    /// Reads the value in place through `f` and subscribes the current
1194    /// scope. Nothing is cloned, so a read of a large value costs nothing
1195    /// beyond `f`; in return `f` borrows the stored value and must not write
1196    /// this state.
1197    pub fn read<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1198        self.read_fresh_subscribed(|inner| inner.state.with_value(f))
1199    }
1200
1201    /// Returns a copy of the value and subscribes the current scope, which recomposes when the
1202    /// value changes. Panics if the state was released.
1203    pub fn value(&self) -> T {
1204        self.read_fresh_subscribed(|inner| inner.state.get())
1205    }
1206
1207    /// Same as `value`.
1208    pub fn get(&self) -> T {
1209        self.value()
1210    }
1211
1212    /// Reads the value without subscribing the current scope or telling a
1213    /// read observer, for a composition that shows it only through a layer
1214    /// or a draw that reads it again.
1215    pub fn get_non_reactive(&self) -> T {
1216        self.with_fresh_inner(|inner| inner.state.value_unobserved())
1217    }
1218
1219    /// The view a derived state hands out of its cell.
1220    fn of_derived(self) -> Self {
1221        Self {
1222            derived: true,
1223            ..self
1224        }
1225    }
1226
1227    /// Runs `f` on the cell, a derived state's once its value is up to date:
1228    /// a read derives the value again when a state it read changed since
1229    /// its derivation last ran, as Compose's `derivedStateOf` does. A plain
1230    /// state's read pays one branch. Panics if the state was released.
1231    fn with_fresh_inner<R>(&self, f: impl FnOnce(&MutableStateInner<T>) -> R) -> R {
1232        runtime::with_state_arena_by_id(self.runtime_id, |arena| {
1233            if self.derived {
1234                arena.refresh_derived(self.id);
1235            }
1236            arena.with_typed::<T, R>(self.id, f)
1237        })
1238        .unwrap_or_else(|| panic!("runtime {:?} dropped", self.runtime_id))
1239    }
1240
1241    /// [`Self::with_fresh_inner`], or `None` if the state was released.
1242    fn try_with_fresh_inner<R>(&self, f: impl FnOnce(&MutableStateInner<T>) -> R) -> Option<R> {
1243        runtime::with_state_arena_by_id(self.runtime_id, |arena| {
1244            if self.derived {
1245                arena.refresh_derived(self.id);
1246            }
1247            arena.with_typed_opt::<T, R>(self.id, f)
1248        })?
1249    }
1250
1251    /// Reads the up-to-date cell through `read` and subscribes the current
1252    /// scope.
1253    fn read_fresh_subscribed<R>(&self, read: impl FnOnce(&MutableStateInner<T>) -> R) -> R {
1254        self.with_fresh_inner(|inner| {
1255            let result = read(inner);
1256            inner.register_current_scope();
1257            result
1258        })
1259    }
1260
1261    /// Returns `true` if any scope or observer is subscribed to this state.
1262    pub fn has_subscribers(&self) -> bool {
1263        self.with_inner(MutableStateInner::has_subscribers)
1264    }
1265
1266    /// Runs `callback` each time this state gains its first subscriber, and
1267    /// right away when it already has one.
1268    ///
1269    /// The state owns `callback` for as long as the state lives, so nothing
1270    /// has to be kept alive on the caller's side.
1271    pub fn on_subscriber(&self, callback: impl Fn() + 'static) {
1272        let callback: Rc<dyn Fn()> = Rc::new(callback);
1273        self.with_inner(|inner| {
1274            inner
1275                .state
1276                .subscribers
1277                .subscriber_callback(callback, inner.has_subscribers());
1278        });
1279    }
1280
1281    /// Counts this state as subscribed for as long as the returned guard
1282    /// lives, without observing it from any scope.
1283    ///
1284    /// Snapshot observers subscribe reads made under composition or the
1285    /// draw phase, and producers gated on [`State::has_subscribers`] — an
1286    /// infinite transition, for one — stop themselves when the last such
1287    /// subscriber leaves. A consumer that reads the value from a polling
1288    /// context (a frame effect stepping it into a derived state, a
1289    /// background task) is invisible to that accounting and would starve
1290    /// the producer it depends on. Holding this guard keeps the producer
1291    /// alive; dropping it releases the count.
1292    pub fn subscription_hold(&self) -> StateSubscriptionHold {
1293        StateSubscriptionHold {
1294            _lease: self
1295                .try_with_inner(|inner| inner.state.observation_lease())
1296                .flatten(),
1297        }
1298    }
1299}
1300
1301/// Keeps a [`State`] counted as subscribed while alive; see
1302/// [`State::subscription_hold`].
1303pub struct StateSubscriptionHold {
1304    _lease: Option<Rc<dyn Any>>,
1305}
1306
1307impl<T: Clone + 'static> StateArenaHandle<T> for MutableState<T> {
1308    fn state_id(&self) -> StateId {
1309        self.id
1310    }
1311
1312    fn runtime_id(&self) -> runtime::RuntimeId {
1313        self.runtime_id
1314    }
1315}
1316
1317// Why a write to `state_id` of `runtime_id` stored nothing: its runtime
1318// was dropped, or the runtime lives and the state was released. Out of line,
1319// one function for every state type.
1320#[cold]
1321#[inline(never)]
1322fn log_skipped_replace(runtime_id: runtime::RuntimeId, state_id: StateId, runtime_alive: bool) {
1323    if runtime_alive {
1324        log::debug!(
1325            "MutableState::replace skipped: state cell released (slot={}, gen={})",
1326            state_id.slot(),
1327            state_id.generation(),
1328        );
1329    } else {
1330        log::debug!("MutableState::replace skipped: runtime {runtime_id:?} dropped");
1331    }
1332}
1333
1334impl<T: Clone + 'static> MutableState<T> {
1335    /// Creates a state holding `value` in `runtime`. Every write counts as a change, even of an
1336    /// equal value. Unless a `remember` owns the state, the runtime keeps it for its own lifetime.
1337    pub fn with_runtime(value: T, runtime: RuntimeHandle) -> Self {
1338        runtime.alloc_persistent_state(value)
1339    }
1340
1341    fn from_parts(id: StateId, runtime_id: runtime::RuntimeId) -> Self {
1342        Self {
1343            id,
1344            runtime_id,
1345            _marker: PhantomData,
1346        }
1347    }
1348
1349    pub(crate) fn from_lease(lease: &Rc<runtime::StateHandleLease>) -> Self {
1350        Self::from_parts(lease.id(), lease.runtime_id())
1351    }
1352
1353    /// Returns `true` while the state exists. It ends when its owner releases it or its runtime is
1354    /// dropped.
1355    pub fn is_alive(&self) -> bool {
1356        self.try_with_inner(|_| ()).is_some()
1357    }
1358
1359    /// Reads the value through `f` without subscribing the current scope. Returns `None` if the
1360    /// state was released or has no readable value.
1361    pub fn try_with<R>(&self, f: impl FnOnce(&T) -> R) -> Option<R> {
1362        self.try_with_inner(|inner| inner.state.try_with_value(f))?
1363    }
1364
1365    /// Returns a copy of the value without subscribing the current scope, or `None` if the state
1366    /// was released or has no readable value.
1367    pub fn try_value(&self) -> Option<T> {
1368        self.try_with_inner(|inner| inner.state.try_get())?
1369    }
1370
1371    /// Returns a read-only view of this state.
1372    pub fn as_state(&self) -> State<T> {
1373        State {
1374            id: self.id,
1375            runtime_id: self.runtime_id,
1376            derived: false,
1377            _marker: PhantomData,
1378        }
1379    }
1380
1381    /// Returns an [`OwnedMutableState`] that keeps this state alive until its last clone is
1382    /// dropped. Returns `None` if the state was already released.
1383    pub fn try_retain(&self) -> Option<OwnedMutableState<T>> {
1384        let lease = self
1385            .runtime_handle_opt()?
1386            .retain_state_lease(self.state_id())?;
1387        Some(OwnedMutableState {
1388            state: *self,
1389            _lease: lease,
1390            _marker: PhantomData,
1391        })
1392    }
1393
1394    /// Returns an [`OwnedMutableState`] that keeps this state alive until its last clone is
1395    /// dropped. Panics if the state was released.
1396    pub fn retain(&self) -> OwnedMutableState<T> {
1397        self.try_retain()
1398            .unwrap_or_else(|| panic!("state {:?} is no longer alive", self.state_id()))
1399    }
1400
1401    /// Reads a copy of the value through `f` and subscribes the current
1402    /// scope. `f` may write this state; see [`Self::read`] for a read that
1403    /// borrows instead of copying.
1404    pub fn with<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1405        let value = self.read_subscribed(|inner| inner.state.get());
1406        f(&value)
1407    }
1408
1409    /// Reads the value in place through `f` and subscribes the current
1410    /// scope. Nothing is cloned, so a read of a large value costs nothing
1411    /// beyond `f`; in return `f` borrows the stored value and must not write
1412    /// this state.
1413    pub fn read<R>(&self, f: impl FnOnce(&T) -> R) -> R {
1414        self.read_subscribed(|inner| inner.state.with_value(f))
1415    }
1416
1417    /// Runs `f` on a copy of the value and stores the copy, unless `f` wrote this state itself.
1418    /// Scopes that read the state are notified if the value changed.
1419    pub fn update<R>(&self, f: impl FnOnce(&mut T) -> R) -> R {
1420        let runtime = self.runtime_handle();
1421        runtime.assert_ui_thread();
1422        runtime.with_state_arena(|arena| {
1423            arena.with_typed::<T, R>(self.state_id(), |inner| {
1424                let mut value = inner.state.get();
1425                let tracker = UpdateScope::new(inner.state.id());
1426                let result = f(&mut value);
1427                let wrote_elsewhere = tracker.finish();
1428                if !wrote_elsewhere && inner.state.set(value) {
1429                    inner.invalidate_watchers();
1430                }
1431                result
1432            })
1433        })
1434    }
1435
1436    /// Stores `value` and notifies the scopes that read the state, if the state's equality policy
1437    /// sees a change. Does nothing if the state was released.
1438    pub fn replace(&self, value: T) {
1439        // The runtimes this thread finds are its own, so a write found here
1440        // is on the runtime's UI thread.
1441        let replaced = runtime::with_state_arena_by_id(self.runtime_id(), |arena| {
1442            arena.with_typed_opt::<T, ()>(self.state_id(), |inner| {
1443                if inner.state.set(value) {
1444                    inner.invalidate_watchers();
1445                }
1446            })
1447        });
1448        if replaced != Some(Some(())) {
1449            log_skipped_replace(self.runtime_id(), self.state_id(), replaced.is_some());
1450        }
1451    }
1452
1453    /// Same as `replace`.
1454    pub fn set_value(&self, value: T) {
1455        self.replace(value);
1456    }
1457
1458    /// Same as `replace`.
1459    pub fn set(&self, value: T) {
1460        self.replace(value);
1461    }
1462
1463    /// Returns a copy of the value and subscribes the current scope, which recomposes when the
1464    /// value changes. Panics if the state was released.
1465    pub fn value(&self) -> T {
1466        self.read_subscribed(|inner| inner.state.get())
1467    }
1468
1469    /// Same as `value`.
1470    pub fn get(&self) -> T {
1471        self.value()
1472    }
1473
1474    /// Returns a copy of the value without subscribing a scope or observer.
1475    pub fn get_non_reactive(&self) -> T {
1476        self.with_inner(|inner| inner.state.value_unobserved())
1477    }
1478
1479    #[doc(hidden)]
1480    pub fn runtime_state_id(&self) -> StateId {
1481        self.state_id()
1482    }
1483
1484    #[doc(hidden)]
1485    pub fn subscribe_current_scope_only(&self) {
1486        self.subscribe_current_scope();
1487    }
1488
1489    fn subscribe_current_scope(&self) {
1490        self.with_inner(MutableStateInner::register_current_scope);
1491    }
1492
1493    #[cfg(test)]
1494    pub(crate) fn watcher_count(&self) -> usize {
1495        self.with_inner(|inner| inner.watchers.scopes.borrow().len())
1496    }
1497
1498    #[cfg(test)]
1499    pub(crate) fn watcher_capacity(&self) -> usize {
1500        self.with_inner(|inner| inner.watchers.scopes.borrow().capacity())
1501    }
1502
1503    #[cfg(test)]
1504    pub(crate) fn state_id_for_test(&self) -> StateId {
1505        self.state_id()
1506    }
1507
1508    #[cfg(test)]
1509    pub(crate) fn subscribe_scope_for_test(&self, scope: &crate::RecomposeScope) {
1510        self.as_state().subscribe_scope_for_test(scope);
1511    }
1512}
1513
1514impl<T: Clone + 'static> OwnedMutableState<T> {
1515    /// Creates a state holding `value` in `runtime`. The state is released when the last clone of
1516    /// this handle is dropped. Every write counts as a change, even of an equal value.
1517    pub fn with_runtime(value: T, runtime: RuntimeHandle) -> Self {
1518        let lease = runtime.alloc_state(value);
1519        Self {
1520            state: MutableState::from_lease(&lease),
1521            _lease: lease,
1522            _marker: PhantomData,
1523        }
1524    }
1525
1526    /// Creates a state holding `value` in `runtime`. Writing a value equal to the current one is
1527    /// not a change.
1528    pub fn with_runtime_structural_eq(value: T, runtime: RuntimeHandle) -> Self
1529    where
1530        T: PartialEq,
1531    {
1532        Self::with_runtime_and_policy(value, runtime, Rc::new(StructuralEqual))
1533    }
1534
1535    pub(crate) fn with_runtime_and_policy(
1536        value: T,
1537        runtime: RuntimeHandle,
1538        policy: Rc<dyn MutationPolicy<T>>,
1539    ) -> Self {
1540        let lease = runtime.alloc_state_with_policy(value, policy);
1541        Self {
1542            state: MutableState::from_lease(&lease),
1543            _lease: lease,
1544            _marker: PhantomData,
1545        }
1546    }
1547
1548    /// Returns the copyable [`MutableState`] handle. It does not keep the state alive.
1549    pub fn handle(&self) -> MutableState<T> {
1550        self.state
1551    }
1552
1553    /// Returns a read-only view of the state.
1554    pub fn as_state(&self) -> State<T> {
1555        self.state.as_state()
1556    }
1557}
1558
1559impl<T: Clone + 'static> Deref for OwnedMutableState<T> {
1560    type Target = MutableState<T>;
1561
1562    fn deref(&self) -> &Self::Target {
1563        &self.state
1564    }
1565}
1566
1567#[cfg(test)]
1568impl<T: Clone + 'static> State<T> {
1569    pub(crate) fn subscribe_scope_for_test(&self, scope: &crate::RecomposeScope) {
1570        self.with_inner(|inner| {
1571            let (registered, became_subscribed) = inner
1572                .watchers
1573                .register_scope(&inner.state.subscribers, scope);
1574            if registered {
1575                if let Some(state_id) = inner.watchers.state_id.get() {
1576                    scope.record_state_subscription(state_id);
1577                }
1578                if became_subscribed {
1579                    inner.state.subscribers.notify_subscribers();
1580                }
1581            }
1582        });
1583    }
1584}
1585
1586impl<T: fmt::Debug + Clone + 'static> fmt::Debug for MutableState<T> {
1587    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1588        if let Some(value) = self.try_value() {
1589            f.debug_struct("MutableState")
1590                .field("value", &value)
1591                .finish()
1592        } else {
1593            f.write_str("MutableState { value: <unavailable> }")
1594        }
1595    }
1596}
1597
1598/// A hash map whose reads subscribe the current scope and whose writes notify its readers, as
1599/// Jetpack Compose's `SnapshotStateMap`. Clones share the same map.
1600#[derive(Clone)]
1601pub struct SnapshotStateMap<K, V>
1602where
1603    K: Clone + Eq + Hash + 'static,
1604    V: Clone + 'static,
1605{
1606    state: OwnedMutableState<HashMap<K, V>>,
1607}
1608
1609impl<K, V> SnapshotStateMap<K, V>
1610where
1611    K: Clone + Eq + Hash + 'static,
1612    V: Clone + 'static,
1613{
1614    /// Creates a map holding `pairs` in `runtime`.
1615    pub fn with_runtime<I>(pairs: I, runtime: RuntimeHandle) -> Self
1616    where
1617        I: IntoIterator<Item = (K, V)>,
1618    {
1619        let map: HashMap<K, V> = pairs.into_iter().collect();
1620        Self {
1621            state: OwnedMutableState::with_runtime(map, runtime),
1622        }
1623    }
1624
1625    /// Returns a read-only view of the state that holds the map.
1626    pub fn as_state(&self) -> State<HashMap<K, V>> {
1627        self.state.as_state()
1628    }
1629
1630    /// Returns the writable state that holds the map.
1631    pub fn as_mutable_state(&self) -> MutableState<HashMap<K, V>> {
1632        self.state.handle()
1633    }
1634
1635    /// Returns the number of entries.
1636    pub fn len(&self) -> usize {
1637        self.state.with(HashMap::len)
1638    }
1639
1640    /// Returns `true` if the map has no entries.
1641    pub fn is_empty(&self) -> bool {
1642        self.state.with(HashMap::is_empty)
1643    }
1644
1645    /// Returns `true` if the map has an entry for `key`.
1646    pub fn contains_key(&self, key: &K) -> bool {
1647        self.state.with(|map| map.contains_key(key))
1648    }
1649
1650    /// Returns a copy of the value under `key`, or `None` if there is none.
1651    pub fn get(&self, key: &K) -> Option<V> {
1652        self.state.with(|map| map.get(key).cloned())
1653    }
1654
1655    /// Returns a copy of the whole map.
1656    pub fn to_hash_map(&self) -> HashMap<K, V> {
1657        self.state.with(Clone::clone)
1658    }
1659
1660    /// Stores `value` under `key` and returns the value it replaced, if any.
1661    pub fn insert(&self, key: K, value: V) -> Option<V> {
1662        self.state.update(|map| map.insert(key, value))
1663    }
1664
1665    /// Inserts all pairs from `iter` in one write, replacing the values of keys already present.
1666    pub fn extend<I>(&self, iter: I)
1667    where
1668        I: IntoIterator<Item = (K, V)>,
1669    {
1670        self.state.update(|map| map.extend(iter));
1671    }
1672
1673    /// Removes the entry under `key` and returns its value, or `None` if there was none.
1674    pub fn remove(&self, key: &K) -> Option<V> {
1675        self.state.update(|map| map.remove(key))
1676    }
1677
1678    /// Removes all entries.
1679    pub fn clear(&self) {
1680        self.state.replace(HashMap::default());
1681    }
1682
1683    /// Keeps the entries for which `predicate` returns `true`. The predicate may change the values
1684    /// it keeps.
1685    pub fn retain<F>(&self, mut predicate: F)
1686    where
1687        F: FnMut(&K, &mut V) -> bool,
1688    {
1689        self.state.update(|map| map.retain(|k, v| predicate(k, v)));
1690    }
1691}
1692
1693impl<K, V> fmt::Debug for SnapshotStateMap<K, V>
1694where
1695    K: Clone + Eq + Hash + fmt::Debug + 'static,
1696    V: Clone + fmt::Debug + 'static,
1697{
1698    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1699        let contents = self.to_hash_map();
1700        f.debug_struct("SnapshotStateMap")
1701            .field("entries", &contents)
1702            .finish()
1703    }
1704}
1705
1706impl<T: fmt::Debug + Clone + 'static> fmt::Debug for State<T> {
1707    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1708        if let Some(value) = self.try_value() {
1709            f.debug_struct("State").field("value", &value).finish()
1710        } else {
1711            f.write_str("State { value: <unavailable> }")
1712        }
1713    }
1714}
1715
1716#[cfg(test)]
1717#[path = "tests/state_tests.rs"]
1718mod tests;