Skip to main content

cranpose_core/
snapshot_state_observer.rs

1use std::{
2    any::{Any, TypeId},
3    cell::{Cell, RefCell},
4    hash::{Hash, Hasher},
5    rc::{Rc, Weak},
6};
7
8use smallvec::SmallVec;
9
10use crate::{
11    collections::map::{HashMap, HashSet},
12    hash::default as default_hash,
13    snapshot_v2::{ReadObserver, TransparentObserverMutableSnapshot, register_apply_observer},
14    state::{ObjectId, StateObject},
15};
16
17type Executor = dyn Fn(Rc<dyn Fn() + 'static>) + 'static;
18
19trait ScopeChangedCallback: Fn(&dyn Any) + Any {}
20
21impl<F: Fn(&dyn Any) + Any> ScopeChangedCallback for F {}
22
23/// Observer that records state object reads performed inside a given scope and
24/// notifies the caller when any of the observed objects change.
25///
26/// This is a pragmatic Rust translation of Jetpack Compose's
27/// `SnapshotStateObserver`. The implementation focuses on the core behaviour
28/// needed by the Cranpose runtime:
29/// - Tracking state object reads per logical scope.
30/// - Reacting to snapshot apply notifications.
31/// - Scheduling invalidation callbacks via the supplied executor.
32///
33/// Advanced features from the Kotlin version (derived state tracking, change
34/// coalescing, queue minimisation) are deferred
35#[derive(Clone)]
36pub struct SnapshotStateObserver {
37    inner: Rc<SnapshotStateObserverInner>,
38}
39
40/// Sizes of a state observer's tables, for leak and memory checks.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub struct SnapshotStateObserverDebugStats {
43    /// Number of scopes with recorded observations.
44    pub scopes_len: usize,
45    /// Capacity reserved for the scope tables.
46    pub scopes_cap: usize,
47    /// Number of scopes that recorded no state reads.
48    pub stateless_scope_count: usize,
49    /// Number of observed states, counted once for each scope that read them.
50    pub observed_state_count: usize,
51    /// Capacity reserved for the observed states of all scopes.
52    pub observed_state_capacity: usize,
53}
54
55impl SnapshotStateObserver {
56    /// Create a new observer that schedules callbacks using `on_changed_executor`.
57    /// The executor runs the task it is given, now or later; the observer
58    /// keeps that task and hands it over again, so scheduling it allocates
59    /// nothing.
60    pub fn new(on_changed_executor: impl Fn(Rc<dyn Fn() + 'static>) + 'static) -> Self {
61        Self {
62            inner: Rc::new_cyclic(|weak| {
63                SnapshotStateObserverInner::new(on_changed_executor, Weak::clone(weak))
64            }),
65        }
66    }
67
68    /// Observe state object reads performed while executing `block`.
69    ///
70    /// Subsequent calls to `observe_reads` replace any previously recorded
71    /// observations for the provided `scope`. When one of the observed objects
72    /// mutates, `on_value_changed_for_scope` will be invoked on the executor.
73    pub fn observe_reads<T, R>(
74        &self,
75        scope: T,
76        on_value_changed_for_scope: impl Fn(&T) + 'static,
77        block: impl FnOnce() -> R,
78    ) -> R
79    where
80        T: Any + Clone + Eq + Hash + 'static,
81    {
82        self.inner
83            .observe_reads(scope, on_value_changed_for_scope, block)
84    }
85
86    /// Temporarily pause read observation while executing `block`.
87    pub fn with_no_observations<R>(&self, block: impl FnOnce() -> R) -> R {
88        self.inner.with_no_observations(block)
89    }
90
91    /// Remove any recorded reads for `scope`.
92    pub fn clear<T>(&self, scope: &T)
93    where
94        T: Any + Eq + Hash + 'static,
95    {
96        self.inner.clear(scope);
97    }
98
99    /// Remove recorded reads for scopes that satisfy `predicate`.
100    pub fn clear_if(&self, predicate: impl Fn(&dyn Any) -> bool) {
101        self.inner.clear_if(&predicate);
102    }
103
104    /// Remove all recorded observations.
105    pub fn clear_all(&self) {
106        self.inner.clear_all();
107    }
108
109    /// Begin listening for snapshot apply notifications.
110    pub fn start(&self) {
111        let weak = Rc::downgrade(&self.inner);
112        self.inner.start(weak);
113    }
114
115    /// Stop listening for snapshot apply notifications.
116    pub fn stop(&self) {
117        self.inner.stop();
118    }
119
120    /// Returns the sizes of the observer's tables, for leak and memory checks.
121    pub fn debug_stats(&self) -> SnapshotStateObserverDebugStats {
122        self.inner.debug_stats()
123    }
124
125    #[cfg(test)]
126    pub(crate) fn notify_changes(&self, modified: &[Rc<dyn StateObject>]) {
127        self.inner.handle_apply(modified);
128    }
129}
130
131struct SnapshotStateObserverInner {
132    executor: Rc<Executor>,
133    owned_scopes: RefCell<HashMap<OwnedScopeIndexKey, OwnedScopeBucket>>,
134    indexed_scopes: RefCell<HashMap<usize, Rc<RefCell<ScopeEntry>>>>,
135    observed_to_scopes: RefCell<HashMap<ObjectId, HashSet<usize>>>,
136    pause_count: Rc<Cell<usize>>,
137    active_read_targets: Rc<RefCell<ReadObservationStack>>,
138    read_dispatcher: ReadObserver,
139    read_snapshot: RefCell<Option<Rc<TransparentObserverMutableSnapshot>>>,
140    apply_handle: RefCell<Option<crate::snapshot_v2::ObserverHandle>>,
141    // The scopes whose states changed, which the flush task notifies, and
142    // that task, with whether it is queued.
143    pending: RefCell<Vec<Rc<RefCell<ScopeEntry>>>>,
144    flush: Rc<dyn Fn() + 'static>,
145    flush_queued: Cell<bool>,
146    next_entry_id: Cell<usize>,
147    /// One `Rc` per type of callback that captures nothing: see
148    /// [`SnapshotStateObserverInner::capture_free_callback`].
149    capture_free_callbacks: RefCell<CaptureFreeCallbacks>,
150}
151
152#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
153struct OwnedScopeIndexKey {
154    type_id: TypeId,
155    value_hash: u64,
156}
157
158type OwnedScopeBucket = SmallVec<[Rc<RefCell<ScopeEntry>>; 1]>;
159
160/// The shared `Rc` of each type of callback that captures nothing.
161type CaptureFreeCallbacks = SmallVec<[(TypeId, Rc<dyn ScopeChangedCallback>); 2]>;
162
163fn owned_scope_index_key<T>(scope: &T) -> OwnedScopeIndexKey
164where
165    T: Any + Hash + 'static,
166{
167    let mut hasher = default_hash::new();
168    scope.hash(&mut hasher);
169    OwnedScopeIndexKey {
170        type_id: TypeId::of::<T>(),
171        value_hash: hasher.finish(),
172    }
173}
174
175impl SnapshotStateObserverInner {
176    const MIN_RETAINED_SCOPE_CAPACITY: usize = 256;
177
178    fn new(
179        on_changed_executor: impl Fn(Rc<dyn Fn() + 'static>) + 'static,
180        weak_self: Weak<Self>,
181    ) -> Self {
182        let pause_count = Rc::new(Cell::new(0));
183        let active_read_targets = Rc::new(RefCell::new(ReadObservationStack::default()));
184        let dispatcher_pause_count = Rc::clone(&pause_count);
185        let dispatcher_targets = Rc::clone(&active_read_targets);
186        let read_dispatcher: ReadObserver = Rc::new(move |state| {
187            if dispatcher_pause_count.get() > 0 {
188                return;
189            }
190            let observed = dispatcher_targets.borrow().last().cloned();
191            if let Some(observed) = observed {
192                observed.borrow_mut().insert(state);
193            }
194        });
195
196        Self {
197            executor: Rc::new(on_changed_executor),
198            owned_scopes: RefCell::new(HashMap::default()),
199            indexed_scopes: RefCell::new(HashMap::default()),
200            observed_to_scopes: RefCell::new(HashMap::default()),
201            pause_count,
202            active_read_targets,
203            read_dispatcher,
204            read_snapshot: RefCell::new(None),
205            apply_handle: RefCell::new(None),
206            pending: RefCell::new(Vec::new()),
207            flush: Rc::new(move || {
208                if let Some(inner) = weak_self.upgrade() {
209                    inner.notify_pending();
210                }
211            }),
212            flush_queued: Cell::new(false),
213            next_entry_id: Cell::new(0),
214            capture_free_callbacks: RefCell::new(SmallVec::new()),
215        }
216    }
217
218    fn observe_reads<T, R>(
219        &self,
220        scope: T,
221        on_value_changed_for_scope: impl Fn(&T) + 'static,
222        block: impl FnOnce() -> R,
223    ) -> R
224    where
225        T: Any + Clone + Eq + Hash + 'static,
226    {
227        let existing_entry = self.find_scope_entry(&scope);
228        let on_changed = std::cell::LazyCell::new(|| {
229            let callback = move |scope_any: &dyn Any| {
230                if let Some(typed) = scope_any.downcast_ref::<T>() {
231                    on_value_changed_for_scope(typed);
232                }
233            };
234            if size_of_val(&callback) == 0 {
235                return self.capture_free_callback(callback);
236            }
237            match existing_entry.as_ref() {
238                Some(entry) => entry.borrow_mut().callback_reusing(callback),
239                None => Rc::new(callback),
240            }
241        });
242
243        if let Some(entry) = existing_entry.as_ref() {
244            entry.borrow_mut().update_scope(&scope);
245            let callback = on_changed.clone();
246            entry.borrow_mut().on_changed = callback;
247        }
248
249        let observed = self.active_read_targets.borrow_mut().push();
250        struct ActiveObservationGuard<'a> {
251            stack: &'a RefCell<ReadObservationStack>,
252        }
253        impl Drop for ActiveObservationGuard<'_> {
254            fn drop(&mut self) {
255                let target = self.stack.borrow_mut().pop();
256                target.borrow_mut().clear();
257            }
258        }
259        let _guard = ActiveObservationGuard {
260            stack: &self.active_read_targets,
261        };
262
263        let result = self.run_with_read_observer(block);
264
265        if observed.borrow().is_empty() {
266            if existing_entry.is_some() {
267                self.clear(&scope);
268            }
269            return result;
270        }
271
272        let callback = Rc::clone(&on_changed);
273        drop(on_changed);
274        let entry = existing_entry
275            .unwrap_or_else(|| self.insert_scope_entry(scope.clone(), Rc::clone(&callback)));
276        entry.borrow_mut().update(&scope, callback);
277        self.replace_observed_ids(&entry, &mut observed.borrow_mut());
278
279        result
280    }
281
282    fn with_no_observations<R>(&self, block: impl FnOnce() -> R) -> R {
283        self.pause_count.set(self.pause_count.get() + 1);
284        let result = block();
285        self.pause_count
286            .set(self.pause_count.get().saturating_sub(1));
287        result
288    }
289
290    fn clear<T>(&self, scope: &T)
291    where
292        T: Any + Eq + Hash + 'static,
293    {
294        let removed = self.remove_scope_entry(scope);
295        if let Some(entry) = removed {
296            self.unregister_entry(&entry);
297        }
298    }
299
300    // One body for every predicate: removals are rare, and a copy for each
301    // caller costs 3 KB of flash on the ESP32.
302    fn clear_if(&self, predicate: &dyn Fn(&dyn Any) -> bool) {
303        let removed = self.partition_scopes(|entry| predicate(entry.scope.as_ref()));
304        for entry in removed {
305            self.unregister_entry(&entry);
306        }
307    }
308
309    fn clear_all(&self) {
310        let entries = std::mem::take(&mut *self.indexed_scopes.borrow_mut());
311        let owned = std::mem::take(&mut *self.owned_scopes.borrow_mut());
312        self.observed_to_scopes.borrow_mut().clear();
313        drop((entries, owned));
314    }
315
316    fn start(&self, weak_self: Weak<Self>) {
317        if self.apply_handle.borrow().is_some() {
318            return;
319        }
320
321        let handle = register_apply_observer(Rc::new(move |modified, _snapshot_id| {
322            if let Some(inner) = weak_self.upgrade() {
323                inner.handle_apply(modified);
324            }
325        }));
326        self.apply_handle.replace(Some(handle));
327    }
328
329    fn stop(&self) {
330        if let Some(handle) = self.apply_handle.borrow_mut().take() {
331            drop(handle);
332        }
333    }
334
335    /// The `Rc` of a callback that captures nothing. Every closure of such a
336    /// type does the same thing, so one `Rc` serves all its scopes instead
337    /// of one each.
338    fn capture_free_callback<F: Fn(&dyn Any) + 'static>(
339        &self,
340        callback: F,
341    ) -> Rc<dyn ScopeChangedCallback> {
342        let type_id = TypeId::of::<F>();
343        let mut shared = self.capture_free_callbacks.borrow_mut();
344        if let Some((_, callback)) = shared.iter().find(|(id, _)| *id == type_id) {
345            return Rc::clone(callback);
346        }
347        let callback: Rc<dyn ScopeChangedCallback> = Rc::new(callback);
348        shared.push((type_id, Rc::clone(&callback)));
349        callback
350    }
351
352    fn insert_scope_entry(
353        &self,
354        scope: impl Any + Clone + Eq + Hash + 'static,
355        on_changed: Rc<dyn ScopeChangedCallback>,
356    ) -> Rc<RefCell<ScopeEntry>> {
357        let entry_id = self.next_entry_id.get();
358        self.next_entry_id.set(entry_id.wrapping_add(1));
359        let scope_key = owned_scope_index_key(&scope);
360        let entry = Rc::new(RefCell::new(ScopeEntry::new(entry_id, scope, on_changed)));
361        self.indexed_scopes
362            .borrow_mut()
363            .insert(entry_id, Rc::clone(&entry));
364        self.owned_scopes
365            .borrow_mut()
366            .entry(scope_key)
367            .or_default()
368            .push(Rc::clone(&entry));
369        entry
370    }
371
372    fn find_scope_entry<T>(&self, scope: &T) -> Option<Rc<RefCell<ScopeEntry>>>
373    where
374        T: Any + Eq + Hash + 'static,
375    {
376        let key = owned_scope_index_key(scope);
377        self.owned_scopes.borrow().get(&key).and_then(|bucket| {
378            bucket
379                .iter()
380                .find(|entry| entry.borrow().matches_scope(scope))
381                .cloned()
382        })
383    }
384
385    fn remove_scope_entry<T>(&self, scope: &T) -> Option<Rc<RefCell<ScopeEntry>>>
386    where
387        T: Any + Eq + Hash + 'static,
388    {
389        let key = owned_scope_index_key(scope);
390        let mut owned_scopes = self.owned_scopes.borrow_mut();
391        let mut removed = None;
392        let mut remove_bucket = false;
393        if let Some(bucket) = owned_scopes.get_mut(&key)
394            && let Some(index) = bucket
395                .iter()
396                .position(|entry| entry.borrow().matches_scope(scope))
397        {
398            removed = Some(bucket.remove(index));
399            remove_bucket = bucket.is_empty();
400        }
401        if remove_bucket {
402            owned_scopes.remove(&key);
403        }
404        shrink_map_if_sparse(&mut owned_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
405        removed
406    }
407
408    fn partition_scopes(
409        &self,
410        should_remove: impl Fn(&ScopeEntry) -> bool,
411    ) -> Vec<Rc<RefCell<ScopeEntry>>> {
412        let mut owned_scopes = self.owned_scopes.borrow_mut();
413        let mut removed = Vec::new();
414        owned_scopes.retain(|_, bucket| {
415            let mut index = 0;
416            while index < bucket.len() {
417                let remove = should_remove(&bucket[index].borrow());
418                if remove {
419                    removed.push(bucket.swap_remove(index));
420                } else {
421                    index += 1;
422                }
423            }
424            !bucket.is_empty()
425        });
426        shrink_map_if_sparse(&mut owned_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
427        removed
428    }
429
430    fn debug_stats(&self) -> SnapshotStateObserverDebugStats {
431        let owned_scopes = self.owned_scopes.borrow();
432        let indexed_scopes = self.indexed_scopes.borrow();
433        let owned_scope_cap =
434            owned_scopes.capacity() + owned_scopes.values().map(SmallVec::capacity).sum::<usize>();
435        let scopes_cap = owned_scope_cap + indexed_scopes.capacity();
436        let mut observed_state_count = 0;
437        let mut observed_state_capacity = 0;
438        let mut stateless_scope_count = 0;
439
440        for entry in indexed_scopes.values() {
441            let entry = entry.borrow();
442            observed_state_count += entry.observed.len();
443            observed_state_capacity += entry.observed.capacity();
444            stateless_scope_count += usize::from(entry.observed.is_empty());
445        }
446
447        SnapshotStateObserverDebugStats {
448            scopes_len: indexed_scopes.len(),
449            scopes_cap,
450            stateless_scope_count,
451            observed_state_count,
452            observed_state_capacity,
453        }
454    }
455
456    fn run_with_read_observer<R>(&self, block: impl FnOnce() -> R) -> R {
457        use crate::snapshot_v2::{
458            current_snapshot_reads_into, take_transparent_observer_mutable_snapshot_reusing,
459        };
460
461        if current_snapshot_reads_into(&self.read_dispatcher) {
462            return block();
463        }
464
465        let mut snapshot = take_transparent_observer_mutable_snapshot_reusing(
466            Some(Rc::clone(&self.read_dispatcher)),
467            None,
468            self.read_snapshot.take(),
469        );
470        let result = snapshot.enter(block);
471        snapshot.dispose();
472        if Rc::get_mut(&mut snapshot).is_some() && !snapshot.has_pending_changes() {
473            self.read_snapshot.replace(Some(snapshot));
474        }
475        result
476    }
477
478    fn handle_apply(&self, modified: &[Rc<dyn StateObject>]) {
479        if modified.is_empty() {
480            return;
481        }
482
483        // One state names each of its scopes once; only several can name
484        // a scope twice.
485        let several = modified.len() > 1;
486        let mut seen_scope_ids: HashSet<usize> = HashSet::default();
487        {
488            let observed_to_scopes = self.observed_to_scopes.borrow();
489            let indexed_scopes = self.indexed_scopes.borrow();
490            let mut pending = self.pending.borrow_mut();
491            for state in modified {
492                if let Some(scope_ids) = observed_to_scopes.get(&state.object_id()) {
493                    let mut ordered_scope_ids: SmallVec<[usize; 8]> =
494                        scope_ids.iter().copied().collect();
495                    ordered_scope_ids.sort_unstable();
496                    pending.reserve(ordered_scope_ids.len());
497                    for scope_id in ordered_scope_ids {
498                        if (!several || seen_scope_ids.insert(scope_id))
499                            && let Some(entry) = indexed_scopes.get(&scope_id)
500                        {
501                            pending.push(Rc::clone(entry));
502                        }
503                    }
504                }
505            }
506            if pending.is_empty() || self.flush_queued.get() {
507                return;
508            }
509        }
510        // One task notifies every scope in turn, as one task a scope would.
511        self.flush_queued.set(true);
512        (self.executor)(Rc::clone(&self.flush));
513    }
514
515    // Notifies the scopes whose states changed since the flush task was
516    // queued. The list keeps its storage for the next change.
517    fn notify_pending(&self) {
518        self.flush_queued.set(false);
519        let mut batch = std::mem::take(&mut *self.pending.borrow_mut());
520        for entry in batch.drain(..) {
521            if let Ok(entry) = entry.try_borrow() {
522                entry.notify();
523            }
524        }
525        let mut pending = self.pending.borrow_mut();
526        if pending.is_empty() {
527            *pending = batch;
528        }
529    }
530
531    fn replace_observed_ids(&self, entry: &Rc<RefCell<ScopeEntry>>, collected: &mut ObservedIds) {
532        let (entry_id, previous) = {
533            let mut entry_mut = entry.borrow_mut();
534            if entry_mut.observed.iter().eq(collected.iter()) {
535                entry_mut.observed.take_leases(collected);
536                collected.clear();
537                return;
538            }
539            let entry_id = entry_mut.id;
540            let previous = std::mem::replace(&mut entry_mut.observed, collected.take_sized());
541            (entry_id, previous)
542        };
543        let entry_ref = entry.borrow();
544        self.unregister_observed_ids(entry_id, &previous);
545        self.register_observed_ids(entry_id, &entry_ref.observed);
546    }
547
548    fn register_observed_ids(&self, entry_id: usize, observed: &ObservedIds) {
549        let mut observed_to_scopes = self.observed_to_scopes.borrow_mut();
550        for state_id in observed.iter() {
551            let scope_ids = observed_to_scopes.entry(state_id).or_default();
552            scope_ids.insert(entry_id);
553        }
554    }
555
556    fn unregister_observed_ids(&self, entry_id: usize, observed: &ObservedIds) {
557        let mut observed_to_scopes = self.observed_to_scopes.borrow_mut();
558        let mut emptied = SmallVec::<[ObjectId; MAX_OBSERVED_STATES]>::new();
559        for state_id in observed.iter() {
560            if let Some(scope_ids) = observed_to_scopes.get_mut(&state_id) {
561                scope_ids.remove(&entry_id);
562                if scope_ids.is_empty() {
563                    emptied.push(state_id);
564                }
565            }
566        }
567        for state_id in emptied {
568            observed_to_scopes.remove(&state_id);
569        }
570        shrink_map_if_sparse(&mut observed_to_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
571    }
572
573    fn unregister_entry(&self, entry: &Rc<RefCell<ScopeEntry>>) {
574        let (entry_id, observed) = {
575            let mut entry_mut = entry.borrow_mut();
576            let observed = std::mem::replace(&mut entry_mut.observed, ObservedIds::new());
577            (entry_mut.id, observed)
578        };
579        self.unregister_observed_ids(entry_id, &observed);
580        self.indexed_scopes.borrow_mut().remove(&entry_id);
581    }
582}
583
584fn shrink_map_if_sparse<K, V>(map: &mut HashMap<K, V>, min_retained_capacity: usize)
585where
586    K: Eq + Hash,
587{
588    if map.capacity() <= map.len().max(min_retained_capacity).saturating_mul(4) {
589        return;
590    }
591
592    let retained = map.len().max(min_retained_capacity);
593    let mut rebuilt = HashMap::default();
594    rebuilt.reserve(retained);
595    rebuilt.extend(map.drain());
596    *map = rebuilt;
597}
598
599#[derive(Default)]
600struct ReadObservationStack {
601    targets: Vec<Rc<RefCell<ObservedIds>>>,
602    depth: usize,
603}
604
605impl ReadObservationStack {
606    fn push(&mut self) -> Rc<RefCell<ObservedIds>> {
607        if self.depth == self.targets.len() {
608            self.targets.push(Rc::new(RefCell::new(ObservedIds::new())));
609        }
610        let target = Rc::clone(&self.targets[self.depth]);
611        self.depth += 1;
612        target
613    }
614
615    fn last(&self) -> Option<&Rc<RefCell<ObservedIds>>> {
616        self.depth.checked_sub(1).map(|index| &self.targets[index])
617    }
618
619    fn pop(&mut self) -> Rc<RefCell<ObservedIds>> {
620        self.depth -= 1;
621        Rc::clone(&self.targets[self.depth])
622    }
623}
624
625#[cfg_attr(
626    feature = "std-hash",
627    expect(
628        clippy::box_collection,
629        reason = "a boxed map keeps the enum the size of its small variant"
630    )
631)]
632enum ObservedIds {
633    Small(SmallVec<[ObservedState; 1]>),
634    Large(Box<HashMap<ObjectId, Option<Rc<dyn Any>>>>),
635}
636
637struct ObservedState {
638    id: ObjectId,
639    _lease: Option<Rc<dyn Any>>,
640}
641
642impl ObservedIds {
643    fn new() -> Self {
644        Self::Small(SmallVec::new())
645    }
646
647    fn insert(&mut self, state: &dyn StateObject) {
648        let id = state.object_id();
649        match self {
650            Self::Small(small) => {
651                if small.iter().any(|observed| observed.id == id) {
652                    return;
653                }
654                if small.len() < MAX_OBSERVED_STATES {
655                    small.push(ObservedState {
656                        id,
657                        _lease: state.observation_lease(),
658                    });
659                } else {
660                    let mut large =
661                        HashMap::with_capacity_and_hasher(small.len() + 1, Default::default());
662                    for observed in small.drain(..) {
663                        large.insert(observed.id, observed._lease);
664                    }
665                    large.insert(id, state.observation_lease());
666                    *self = Self::Large(Box::new(large));
667                }
668            }
669            Self::Large(large) => {
670                large.entry(id).or_insert_with(|| state.observation_lease());
671            }
672        }
673    }
674
675    fn clear(&mut self) {
676        match self {
677            Self::Small(small) => small.clear(),
678            Self::Large(_) => *self = Self::new(),
679        }
680    }
681
682    /// Keeps `fresh`'s observation leases for the states both name, leaving
683    /// the old ones in `fresh` to drop. An id is a state's address, which a
684    /// new state can take after the old one is dropped, and only its own
685    /// lease keeps the new one observed.
686    fn take_leases(&mut self, fresh: &mut Self) {
687        match (self, fresh) {
688            (Self::Small(kept), Self::Small(fresh)) => {
689                for (kept, fresh) in kept.iter_mut().zip(fresh.iter_mut()) {
690                    std::mem::swap(&mut kept._lease, &mut fresh._lease);
691                }
692            }
693            (kept, fresh) => std::mem::swap(kept, fresh),
694        }
695    }
696
697    fn take_sized(&mut self) -> Self {
698        match self {
699            Self::Small(small) => Self::Small(small.drain(..).collect()),
700            Self::Large(_) => std::mem::replace(self, Self::new()),
701        }
702    }
703
704    fn is_empty(&self) -> bool {
705        match self {
706            Self::Small(small) => small.is_empty(),
707            Self::Large(large) => large.is_empty(),
708        }
709    }
710
711    fn len(&self) -> usize {
712        match self {
713            Self::Small(small) => small.len(),
714            Self::Large(large) => large.len(),
715        }
716    }
717
718    fn capacity(&self) -> usize {
719        match self {
720            Self::Small(small) => small.capacity(),
721            Self::Large(large) => large.capacity(),
722        }
723    }
724
725    fn iter(&self) -> impl Iterator<Item = ObjectId> + '_ {
726        let (small, large) = match self {
727            Self::Small(small) => (Some(small.as_slice()), None),
728            Self::Large(large) => (None, Some(large)),
729        };
730        small
731            .into_iter()
732            .flatten()
733            .map(|observed| observed.id)
734            .chain(large.into_iter().flat_map(|states| states.keys().copied()))
735    }
736}
737
738const MAX_OBSERVED_STATES: usize = 8;
739
740struct ScopeEntry {
741    id: usize,
742    scope: Box<dyn Any>,
743    on_changed: Rc<dyn ScopeChangedCallback>,
744    observed: ObservedIds,
745}
746
747impl ScopeEntry {
748    fn new<T>(id: usize, scope: T, on_changed: Rc<dyn ScopeChangedCallback>) -> Self
749    where
750        T: Any + 'static,
751    {
752        Self {
753            id,
754            scope: Box::new(scope),
755            on_changed,
756            observed: ObservedIds::new(),
757        }
758    }
759
760    fn callback_reusing<F: Fn(&dyn Any) + 'static>(
761        &mut self,
762        callback: F,
763    ) -> Rc<dyn ScopeChangedCallback> {
764        if let Some(stored) = Rc::get_mut(&mut self.on_changed)
765            .and_then(|stored| (stored as &mut dyn Any).downcast_mut::<F>())
766        {
767            *stored = callback;
768            Rc::clone(&self.on_changed)
769        } else {
770            Rc::new(callback)
771        }
772    }
773
774    fn update<T>(&mut self, new_scope: &T, on_changed: Rc<dyn ScopeChangedCallback>)
775    where
776        T: Any + Clone + 'static,
777    {
778        self.update_scope(new_scope);
779        self.on_changed = on_changed;
780    }
781
782    fn update_scope<T>(&mut self, new_scope: &T)
783    where
784        T: Any + Clone + 'static,
785    {
786        match self.scope.downcast_mut::<T>() {
787            Some(stored) => stored.clone_from(new_scope),
788            None => self.scope = Box::new(new_scope.clone()),
789        }
790    }
791
792    fn matches_scope<T>(&self, scope: &T) -> bool
793    where
794        T: Any + Eq + 'static,
795    {
796        self.scope
797            .downcast_ref::<T>()
798            .is_some_and(|stored| stored == scope)
799    }
800
801    fn notify(&self) {
802        (self.on_changed)(self.scope.as_ref());
803    }
804}
805
806#[cfg(test)]
807#[path = "tests/snapshot_state_observer_tests.rs"]
808mod tests;