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