cranpose-core 0.1.164

Core runtime for a Jetpack Compose inspired UI framework in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
use std::{
    any::{Any, TypeId},
    cell::{Cell, RefCell},
    hash::{Hash, Hasher},
    rc::{Rc, Weak},
    sync::Arc,
};

use smallvec::SmallVec;

use crate::{
    RecomposeScope, RecomposeScopeInner, ScopeId,
    collections::map::{HashMap, HashSet},
    hash::default as default_hash,
    snapshot_v2::{
        ReadObserver, StateObjectId, TransparentObserverMutableSnapshot, register_apply_observer,
    },
    state::StateObject,
};

type Executor = dyn Fn(Box<dyn FnOnce() + 'static>) + 'static;

trait ScopeChangedCallback: Fn(&dyn Any) + Any {}

impl<F: Fn(&dyn Any) + Any> ScopeChangedCallback for F {}

/// Observer that records state object reads performed inside a given scope and
/// notifies the caller when any of the observed objects change.
///
/// This is a pragmatic Rust translation of Jetpack Compose's
/// `SnapshotStateObserver`. The implementation focuses on the core behaviour
/// needed by the Cranpose runtime:
/// - Tracking state object reads per logical scope.
/// - Reacting to snapshot apply notifications.
/// - Scheduling invalidation callbacks via the supplied executor.
///
/// Advanced features from the Kotlin version (derived state tracking, change
/// coalescing, queue minimisation) are deferred
#[derive(Clone)]
pub struct SnapshotStateObserver {
    inner: Rc<SnapshotStateObserverInner>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct SnapshotStateObserverDebugStats {
    pub scopes_len: usize,
    pub scopes_cap: usize,
    pub fast_scopes_len: usize,
    pub fast_scopes_cap: usize,
    pub stateless_scope_count: usize,
    pub observed_state_count: usize,
    pub observed_state_capacity: usize,
}

impl SnapshotStateObserver {
    /// Create a new observer that schedules callbacks using `on_changed_executor`.
    pub fn new(on_changed_executor: impl Fn(Box<dyn FnOnce() + 'static>) + 'static) -> Self {
        let inner = Rc::new(SnapshotStateObserverInner::new(on_changed_executor));
        inner.set_self(Rc::downgrade(&inner));
        Self { inner }
    }

    /// Observe state object reads performed while executing `block`.
    ///
    /// Subsequent calls to `observe_reads` replace any previously recorded
    /// observations for the provided `scope`. When one of the observed objects
    /// mutates, `on_value_changed_for_scope` will be invoked on the executor.
    pub fn observe_reads<T, R>(
        &self,
        scope: T,
        on_value_changed_for_scope: impl Fn(&T) + 'static,
        block: impl FnOnce() -> R,
    ) -> R
    where
        T: Any + Clone + Eq + Hash + 'static,
    {
        self.inner
            .observe_reads(scope, on_value_changed_for_scope, block)
    }

    /// Notify the observer that a new composition frame is starting.
    pub fn begin_frame(&self) {
        self.inner.begin_frame();
    }

    /// Drop bookkeeping for scopes that were released during the current frame.
    pub fn prune_dead_scopes(&self) {
        self.inner.prune_dead_scopes();
    }

    /// Temporarily pause read observation while executing `block`.
    pub fn with_no_observations<R>(&self, block: impl FnOnce() -> R) -> R {
        self.inner.with_no_observations(block)
    }

    /// Remove any recorded reads for `scope`.
    pub fn clear<T>(&self, scope: &T)
    where
        T: Any + Eq + Hash + 'static,
    {
        self.inner.clear(scope);
    }

    /// Remove recorded reads for scopes that satisfy `predicate`.
    pub fn clear_if(&self, predicate: impl Fn(&dyn Any) -> bool) {
        self.inner.clear_if(predicate);
    }

    /// Remove all recorded observations.
    pub fn clear_all(&self) {
        self.inner.clear_all();
    }

    /// Begin listening for snapshot apply notifications.
    pub fn start(&self) {
        let weak = Rc::downgrade(&self.inner);
        self.inner.start(weak);
    }

    /// Stop listening for snapshot apply notifications.
    pub fn stop(&self) {
        self.inner.stop();
    }

    pub fn debug_stats(&self) -> SnapshotStateObserverDebugStats {
        self.inner.debug_stats()
    }

    #[cfg(test)]
    pub fn notify_changes(&self, modified: &[Arc<dyn StateObject>]) {
        self.inner.handle_apply(modified);
    }
}

struct SnapshotStateObserverInner {
    executor: Rc<Executor>,
    owned_scopes: RefCell<HashMap<OwnedScopeIndexKey, OwnedScopeBucket>>,
    fast_scopes: RefCell<HashMap<ScopeId, Rc<RefCell<ScopeEntry>>>>,
    indexed_scopes: RefCell<HashMap<usize, Rc<RefCell<ScopeEntry>>>>,
    observed_to_scopes: RefCell<HashMap<StateObjectId, HashSet<usize>>>,
    pause_count: Rc<Cell<usize>>,
    active_read_targets: Rc<RefCell<ReadObservationStack>>,
    read_dispatcher: ReadObserver,
    read_snapshot: RefCell<Option<Arc<TransparentObserverMutableSnapshot>>>,
    apply_handle: RefCell<Option<crate::snapshot_v2::ObserverHandle>>,
    weak_self: RefCell<Weak<SnapshotStateObserverInner>>,
    frame_version: Cell<u64>,
    next_entry_id: Cell<usize>,
}

#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
struct OwnedScopeIndexKey {
    type_id: TypeId,
    value_hash: u64,
}

type OwnedScopeBucket = SmallVec<[Rc<RefCell<ScopeEntry>>; 1]>;

fn owned_scope_index_key<T>(scope: &T) -> OwnedScopeIndexKey
where
    T: Any + Hash + 'static,
{
    let mut hasher = default_hash::new();
    scope.hash(&mut hasher);
    OwnedScopeIndexKey {
        type_id: TypeId::of::<T>(),
        value_hash: hasher.finish(),
    }
}

impl SnapshotStateObserverInner {
    const MIN_RETAINED_SCOPE_CAPACITY: usize = 256;

    fn new(on_changed_executor: impl Fn(Box<dyn FnOnce() + 'static>) + 'static) -> Self {
        let pause_count = Rc::new(Cell::new(0));
        let active_read_targets = Rc::new(RefCell::new(ReadObservationStack::default()));
        let dispatcher_pause_count = Rc::clone(&pause_count);
        let dispatcher_targets = Rc::clone(&active_read_targets);
        let read_dispatcher: ReadObserver = Arc::new(move |state| {
            if dispatcher_pause_count.get() > 0 {
                return;
            }
            let observed = dispatcher_targets.borrow().last().cloned();
            if let Some(observed) = observed {
                observed.borrow_mut().insert(state);
            }
        });

        Self {
            executor: Rc::new(on_changed_executor),
            owned_scopes: RefCell::new(HashMap::default()),
            fast_scopes: RefCell::new(HashMap::default()),
            indexed_scopes: RefCell::new(HashMap::default()),
            observed_to_scopes: RefCell::new(HashMap::default()),
            pause_count,
            active_read_targets,
            read_dispatcher,
            read_snapshot: RefCell::new(None),
            apply_handle: RefCell::new(None),
            weak_self: RefCell::new(Weak::new()),
            frame_version: Cell::new(0),
            next_entry_id: Cell::new(0),
        }
    }

    fn set_self(&self, weak: Weak<SnapshotStateObserverInner>) {
        self.weak_self.replace(weak);
    }

    fn begin_frame(&self) {
        let next = self.frame_version.get().wrapping_add(1);
        self.frame_version.set(next);
        self.prune_dead_scopes();
    }

    fn observe_reads<T, R>(
        &self,
        scope: T,
        on_value_changed_for_scope: impl Fn(&T) + 'static,
        block: impl FnOnce() -> R,
    ) -> R
    where
        T: Any + Clone + Eq + Hash + 'static,
    {
        let frame_version = self.frame_version.get();
        let has_frame_version = frame_version != 0;

        let existing_entry = self.find_scope_entry(&scope);
        let on_changed = std::cell::LazyCell::new(|| {
            let callback = move |scope_any: &dyn Any| {
                if let Some(typed) = scope_any.downcast_ref::<T>() {
                    on_value_changed_for_scope(typed);
                }
            };
            match existing_entry.as_ref() {
                Some(entry) => entry.borrow_mut().callback_reusing(callback),
                None => Rc::new(callback),
            }
        });

        if let Some(entry) = existing_entry.as_ref() {
            let already_observed = {
                let mut entry_mut = entry.borrow_mut();
                entry_mut.update_scope(scope.clone());
                has_frame_version && entry_mut.last_seen_version == frame_version
            };
            let callback = on_changed.clone();
            entry.borrow_mut().on_changed = callback;
            if already_observed {
                return block();
            }
        }

        let observed = self.active_read_targets.borrow_mut().push();
        struct ActiveObservationGuard {
            stack: Rc<RefCell<ReadObservationStack>>,
        }
        impl Drop for ActiveObservationGuard {
            fn drop(&mut self) {
                let target = self.stack.borrow_mut().pop();
                let discarded = target.replace(ObservedIds::new());
                drop(discarded);
            }
        }
        let _guard = ActiveObservationGuard {
            stack: Rc::clone(&self.active_read_targets),
        };

        let result = self.run_with_read_observer(block);

        if observed.borrow().is_empty() {
            if existing_entry.is_some() {
                self.clear(&scope);
            }
            return result;
        }

        let observed = {
            let mut observed = observed.borrow_mut();
            std::mem::replace(&mut *observed, ObservedIds::new())
        };
        let entry = existing_entry
            .clone()
            .unwrap_or_else(|| self.insert_scope_entry(scope.clone(), on_changed.clone()));
        {
            let mut entry_mut = entry.borrow_mut();
            entry_mut.update(scope, Rc::clone(&on_changed));
            entry_mut.last_seen_version = if has_frame_version {
                frame_version
            } else {
                u64::MAX
            };
        }
        self.replace_observed_ids(&entry, observed);

        result
    }

    fn with_no_observations<R>(&self, block: impl FnOnce() -> R) -> R {
        self.pause_count.set(self.pause_count.get() + 1);
        let result = block();
        self.pause_count
            .set(self.pause_count.get().saturating_sub(1));
        result
    }

    fn clear<T>(&self, scope: &T)
    where
        T: Any + Eq + Hash + 'static,
    {
        if let Some(rc_scope) = (scope as &dyn Any).downcast_ref::<RecomposeScope>() {
            if let Some(entry) = self.fast_scopes.borrow_mut().remove(&rc_scope.id()) {
                self.unregister_entry(&entry);
            }
            return;
        }

        let removed = self.remove_owned_scope_entry(scope);
        if let Some(entry) = removed {
            self.unregister_entry(&entry);
        }
    }

    fn clear_if(&self, predicate: impl Fn(&dyn Any) -> bool) {
        let removed_fast = {
            let mut fast_scopes = self.fast_scopes.borrow_mut();
            let removed_ids: Vec<_> = fast_scopes
                .iter()
                .filter(|(_, entry)| entry.borrow().matches_predicate(&predicate))
                .map(|(scope_id, _)| *scope_id)
                .collect();
            removed_ids
                .into_iter()
                .filter_map(|scope_id| fast_scopes.remove(&scope_id))
                .collect::<Vec<_>>()
        };
        let removed_owned =
            { self.partition_owned_scopes(|entry| entry.matches_predicate(&predicate)) };

        for entry in removed_fast.into_iter().chain(removed_owned) {
            self.unregister_entry(&entry);
        }
    }

    fn clear_all(&self) {
        self.fast_scopes.borrow_mut().clear();
        self.owned_scopes.borrow_mut().clear();
        self.indexed_scopes.borrow_mut().clear();
        self.observed_to_scopes.borrow_mut().clear();
    }

    fn start(&self, weak_self: Weak<SnapshotStateObserverInner>) {
        if self.apply_handle.borrow().is_some() {
            return;
        }

        let handle = register_apply_observer(Rc::new(move |modified, _snapshot_id| {
            if let Some(inner) = weak_self.upgrade() {
                inner.handle_apply(modified);
            }
        }));
        self.apply_handle.replace(Some(handle));
    }

    fn stop(&self) {
        if let Some(handle) = self.apply_handle.borrow_mut().take() {
            drop(handle);
        }
    }

    fn find_scope_entry<T>(&self, scope: &T) -> Option<Rc<RefCell<ScopeEntry>>>
    where
        T: Any + Eq + Hash + 'static,
    {
        if let Some(scope) = (scope as &dyn Any).downcast_ref::<RecomposeScope>() {
            return self.fast_scopes.borrow().get(&scope.id()).cloned();
        }

        self.find_owned_scope_entry(scope)
    }

    fn insert_scope_entry(
        &self,
        scope: impl Any + Clone + Eq + Hash + 'static,
        on_changed: Rc<dyn ScopeChangedCallback>,
    ) -> Rc<RefCell<ScopeEntry>> {
        let entry_id = self.next_entry_id.get();
        self.next_entry_id.set(entry_id.wrapping_add(1));
        let recompose_scope_id = (&scope as &dyn Any)
            .downcast_ref::<RecomposeScope>()
            .map(RecomposeScope::id);
        let owned_scope_key = recompose_scope_id
            .is_none()
            .then(|| owned_scope_index_key(&scope));
        let entry = Rc::new(RefCell::new(ScopeEntry::new(entry_id, scope, on_changed)));
        self.indexed_scopes
            .borrow_mut()
            .insert(entry_id, Rc::clone(&entry));
        if let Some(scope_id) = recompose_scope_id {
            self.fast_scopes
                .borrow_mut()
                .insert(scope_id, Rc::clone(&entry));
        } else if let Some(scope_key) = owned_scope_key {
            self.owned_scopes
                .borrow_mut()
                .entry(scope_key)
                .or_default()
                .push(Rc::clone(&entry));
        }
        entry
    }

    fn prune_dead_scopes(&self) {
        let removed_fast = {
            let mut fast_scopes = self.fast_scopes.borrow_mut();
            let removed_ids: Vec<_> = fast_scopes
                .iter()
                .filter(|(_, entry)| !entry.borrow().should_retain())
                .map(|(scope_id, _)| *scope_id)
                .collect();
            let removed = removed_ids
                .into_iter()
                .filter_map(|scope_id| fast_scopes.remove(&scope_id))
                .collect::<Vec<_>>();
            shrink_map_if_sparse(&mut fast_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
            removed
        };

        let removed_owned = { self.partition_owned_scopes(|entry| !entry.should_retain()) };

        for entry in removed_fast.into_iter().chain(removed_owned) {
            self.unregister_entry(&entry);
        }
    }

    fn find_owned_scope_entry<T>(&self, scope: &T) -> Option<Rc<RefCell<ScopeEntry>>>
    where
        T: Any + Eq + Hash + 'static,
    {
        let key = owned_scope_index_key(scope);
        self.owned_scopes.borrow().get(&key).and_then(|bucket| {
            bucket
                .iter()
                .find(|entry| entry.borrow().matches_scope(scope))
                .cloned()
        })
    }

    fn remove_owned_scope_entry<T>(&self, scope: &T) -> Option<Rc<RefCell<ScopeEntry>>>
    where
        T: Any + Eq + Hash + 'static,
    {
        let key = owned_scope_index_key(scope);
        let mut owned_scopes = self.owned_scopes.borrow_mut();
        let mut removed = None;
        let mut remove_bucket = false;
        if let Some(bucket) = owned_scopes.get_mut(&key)
            && let Some(index) = bucket
                .iter()
                .position(|entry| entry.borrow().matches_scope(scope))
        {
            removed = Some(bucket.remove(index));
            remove_bucket = bucket.is_empty();
        }
        if remove_bucket {
            owned_scopes.remove(&key);
        }
        shrink_map_if_sparse(&mut owned_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
        removed
    }

    fn partition_owned_scopes(
        &self,
        should_remove: impl Fn(&ScopeEntry) -> bool,
    ) -> Vec<Rc<RefCell<ScopeEntry>>> {
        let mut owned_scopes = self.owned_scopes.borrow_mut();
        let mut retained = HashMap::default();
        let mut removed = Vec::new();
        for (key, mut bucket) in owned_scopes.drain() {
            let mut retained_bucket = OwnedScopeBucket::new();
            for entry in bucket.drain(..) {
                if should_remove(&entry.borrow()) {
                    removed.push(entry);
                } else {
                    retained_bucket.push(entry);
                }
            }
            if !retained_bucket.is_empty() {
                retained.insert(key, retained_bucket);
            }
        }
        *owned_scopes = retained;
        shrink_map_if_sparse(&mut owned_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
        removed
    }

    fn debug_stats(&self) -> SnapshotStateObserverDebugStats {
        let owned_scopes = self.owned_scopes.borrow();
        let fast_scopes = self.fast_scopes.borrow();
        let owned_scope_len = owned_scopes.values().map(SmallVec::len).sum::<usize>();
        let owned_scope_cap =
            owned_scopes.capacity() + owned_scopes.values().map(SmallVec::capacity).sum::<usize>();
        let scopes_len = owned_scope_len + fast_scopes.len();
        let scopes_cap = owned_scope_cap + fast_scopes.capacity();
        let mut observed_state_count = 0;
        let mut observed_state_capacity = 0;
        let mut stateless_scope_count = 0;

        for entry in owned_scopes
            .values()
            .flat_map(|bucket| bucket.iter())
            .chain(fast_scopes.values())
        {
            let entry = entry.borrow();
            observed_state_count += entry.observed.len();
            observed_state_capacity += entry.observed.capacity();
            stateless_scope_count += usize::from(entry.observed.is_empty());
        }

        SnapshotStateObserverDebugStats {
            scopes_len,
            scopes_cap,
            fast_scopes_len: fast_scopes.len(),
            fast_scopes_cap: fast_scopes.capacity(),
            stateless_scope_count,
            observed_state_count,
            observed_state_capacity,
        }
    }

    fn run_with_read_observer<R>(&self, block: impl FnOnce() -> R) -> R {
        use crate::snapshot_v2::take_transparent_observer_mutable_snapshot_reusing;

        let mut snapshot = take_transparent_observer_mutable_snapshot_reusing(
            Some(self.read_dispatcher.clone()),
            None,
            self.read_snapshot.take(),
        );
        let result = snapshot.enter(block);
        snapshot.dispose();
        if Arc::get_mut(&mut snapshot).is_some() && !snapshot.has_pending_changes() {
            self.read_snapshot.replace(Some(snapshot));
        }
        result
    }

    fn handle_apply(&self, modified: &[Arc<dyn StateObject>]) {
        if modified.is_empty() {
            return;
        }

        let mut seen_scope_ids: HashSet<usize> = HashSet::default();
        let mut to_notify: Vec<Rc<RefCell<ScopeEntry>>> = Vec::new();
        {
            let observed_to_scopes = self.observed_to_scopes.borrow();
            let indexed_scopes = self.indexed_scopes.borrow();
            for state in modified {
                if let Some(scope_ids) = observed_to_scopes.get(&state.object_id().as_usize()) {
                    let mut ordered_scope_ids: SmallVec<[usize; 8]> =
                        scope_ids.iter().copied().collect();
                    ordered_scope_ids.sort_unstable();
                    for scope_id in ordered_scope_ids {
                        if seen_scope_ids.insert(scope_id)
                            && let Some(entry) = indexed_scopes.get(&scope_id)
                        {
                            to_notify.push(entry.clone());
                        }
                    }
                }
            }
        }

        if to_notify.is_empty() {
            return;
        }

        for entry in to_notify {
            let executor = self.executor.clone();
            executor(Box::new(move || {
                if let Ok(entry) = entry.try_borrow() {
                    entry.notify();
                }
            }));
        }
    }

    fn replace_observed_ids(&self, entry: &Rc<RefCell<ScopeEntry>>, observed: ObservedIds) {
        let (entry_id, previous) = {
            let mut entry_mut = entry.borrow_mut();
            let entry_id = entry_mut.id;
            let previous = std::mem::replace(&mut entry_mut.observed, observed);
            (entry_id, previous)
        };
        let entry_ref = entry.borrow();
        if previous.iter().eq(entry_ref.observed.iter()) {
            return;
        }
        self.unregister_observed_ids(entry_id, &previous);
        self.register_observed_ids(entry_id, &entry_ref.observed);
    }

    fn register_observed_ids(&self, entry_id: usize, observed: &ObservedIds) {
        let mut observed_to_scopes = self.observed_to_scopes.borrow_mut();
        for state_id in observed.iter() {
            let scope_ids = observed_to_scopes.entry(state_id).or_default();
            scope_ids.insert(entry_id);
        }
    }

    fn unregister_observed_ids(&self, entry_id: usize, observed: &ObservedIds) {
        let mut observed_to_scopes = self.observed_to_scopes.borrow_mut();
        let mut emptied = SmallVec::<[StateObjectId; MAX_OBSERVED_STATES]>::new();
        for state_id in observed.iter() {
            if let Some(scope_ids) = observed_to_scopes.get_mut(&state_id) {
                scope_ids.remove(&entry_id);
                if scope_ids.is_empty() {
                    emptied.push(state_id);
                }
            }
        }
        for state_id in emptied {
            observed_to_scopes.remove(&state_id);
        }
        shrink_map_if_sparse(&mut observed_to_scopes, Self::MIN_RETAINED_SCOPE_CAPACITY);
    }

    fn unregister_entry(&self, entry: &Rc<RefCell<ScopeEntry>>) {
        let (entry_id, observed) = {
            let mut entry_mut = entry.borrow_mut();
            let observed = std::mem::replace(&mut entry_mut.observed, ObservedIds::new());
            (entry_mut.id, observed)
        };
        self.unregister_observed_ids(entry_id, &observed);
        self.indexed_scopes.borrow_mut().remove(&entry_id);
    }
}

fn shrink_map_if_sparse<K, V>(map: &mut HashMap<K, V>, min_retained_capacity: usize)
where
    K: Eq + std::hash::Hash,
{
    if map.capacity() <= map.len().max(min_retained_capacity).saturating_mul(4) {
        return;
    }

    let retained = map.len().max(min_retained_capacity);
    let mut rebuilt = HashMap::default();
    rebuilt.reserve(retained);
    rebuilt.extend(map.drain());
    *map = rebuilt;
}

#[derive(Default)]
struct ReadObservationStack {
    targets: Vec<Rc<RefCell<ObservedIds>>>,
    depth: usize,
}

impl ReadObservationStack {
    fn push(&mut self) -> Rc<RefCell<ObservedIds>> {
        if self.depth == self.targets.len() {
            self.targets.push(Rc::new(RefCell::new(ObservedIds::new())));
        }
        let target = Rc::clone(&self.targets[self.depth]);
        self.depth += 1;
        target
    }

    fn last(&self) -> Option<&Rc<RefCell<ObservedIds>>> {
        self.depth.checked_sub(1).map(|index| &self.targets[index])
    }

    fn pop(&mut self) -> Rc<RefCell<ObservedIds>> {
        self.depth -= 1;
        Rc::clone(&self.targets[self.depth])
    }
}

enum ObservedIds {
    Small(SmallVec<[ObservedState; MAX_OBSERVED_STATES]>),
    Large(HashMap<StateObjectId, Option<Rc<dyn Any>>>),
}

struct ObservedState {
    id: StateObjectId,
    _lease: Option<Rc<dyn Any>>,
}

impl ObservedIds {
    fn new() -> Self {
        ObservedIds::Small(SmallVec::new())
    }

    fn insert(&mut self, state: &dyn StateObject) {
        let id = state.object_id().as_usize();
        match self {
            ObservedIds::Small(small) => {
                if small.iter().any(|observed| observed.id == id) {
                    return;
                }
                if small.len() < MAX_OBSERVED_STATES {
                    small.push(ObservedState {
                        id,
                        _lease: state.observation_lease(),
                    });
                } else {
                    let mut large =
                        HashMap::with_capacity_and_hasher(small.len() + 1, Default::default());
                    for observed in small.drain(..) {
                        large.insert(observed.id, observed._lease);
                    }
                    large.insert(id, state.observation_lease());
                    *self = ObservedIds::Large(large);
                }
            }
            ObservedIds::Large(large) => {
                large.entry(id).or_insert_with(|| state.observation_lease());
            }
        }
    }

    fn is_empty(&self) -> bool {
        match self {
            ObservedIds::Small(small) => small.is_empty(),
            ObservedIds::Large(large) => large.is_empty(),
        }
    }

    fn len(&self) -> usize {
        match self {
            ObservedIds::Small(small) => small.len(),
            ObservedIds::Large(large) => large.len(),
        }
    }

    fn capacity(&self) -> usize {
        match self {
            ObservedIds::Small(small) => small.capacity(),
            ObservedIds::Large(large) => large.capacity(),
        }
    }

    fn iter(&self) -> impl Iterator<Item = StateObjectId> + '_ {
        let (small, large) = match self {
            ObservedIds::Small(small) => (Some(small.as_slice()), None),
            ObservedIds::Large(large) => (None, Some(large)),
        };
        small
            .into_iter()
            .flatten()
            .map(|observed| observed.id)
            .chain(large.into_iter().flat_map(|states| states.keys().copied()))
    }
}

const MAX_OBSERVED_STATES: usize = 8;

enum ScopeStorage {
    Owned(Box<dyn Any>),
    RecomposeScope {
        id: ScopeId,
        weak: Weak<RecomposeScopeInner>,
    },
}

struct ScopeEntry {
    id: usize,
    scope: ScopeStorage,
    on_changed: Rc<dyn ScopeChangedCallback>,
    observed: ObservedIds,
    last_seen_version: u64,
}

impl ScopeEntry {
    fn new<T>(id: usize, scope: T, on_changed: Rc<dyn ScopeChangedCallback>) -> Self
    where
        T: Any + 'static,
    {
        Self {
            id,
            scope: ScopeStorage::from_value(scope),
            on_changed,
            observed: ObservedIds::new(),
            last_seen_version: u64::MAX,
        }
    }

    fn callback_reusing<F: Fn(&dyn Any) + 'static>(
        &mut self,
        callback: F,
    ) -> Rc<dyn ScopeChangedCallback> {
        if let Some(stored) = Rc::get_mut(&mut self.on_changed)
            .and_then(|stored| (stored as &mut dyn Any).downcast_mut::<F>())
        {
            *stored = callback;
            Rc::clone(&self.on_changed)
        } else {
            Rc::new(callback)
        }
    }

    fn update<T>(&mut self, new_scope: T, on_changed: Rc<dyn ScopeChangedCallback>)
    where
        T: Any + 'static,
    {
        self.update_scope(new_scope);
        self.on_changed = on_changed;
    }

    fn update_scope<T>(&mut self, new_scope: T)
    where
        T: Any + 'static,
    {
        if let ScopeStorage::Owned(stored) = &mut self.scope
            && let Some(stored) = stored.downcast_mut::<T>()
        {
            *stored = new_scope;
        } else {
            self.scope = ScopeStorage::from_value(new_scope);
        }
    }

    fn matches_scope<T>(&self, scope: &T) -> bool
    where
        T: Any + Eq + 'static,
    {
        if let Some(scope) = (scope as &dyn Any).downcast_ref::<RecomposeScope>() {
            return matches!(
                &self.scope,
                ScopeStorage::RecomposeScope { id, .. } if *id == scope.id()
            );
        }

        match &self.scope {
            ScopeStorage::Owned(stored) => stored
                .downcast_ref::<T>()
                .is_some_and(|stored| stored == scope),
            ScopeStorage::RecomposeScope { .. } => false,
        }
    }

    fn matches_predicate(&self, predicate: &impl Fn(&dyn Any) -> bool) -> bool {
        match &self.scope {
            ScopeStorage::Owned(scope) => predicate(scope.as_ref()),
            ScopeStorage::RecomposeScope { weak, .. } => weak
                .upgrade()
                .is_none_or(|inner| predicate(&RecomposeScope { inner })),
        }
    }

    fn should_retain(&self) -> bool {
        match &self.scope {
            ScopeStorage::Owned(_) => true,
            ScopeStorage::RecomposeScope { weak, .. } => weak.upgrade().is_some(),
        }
    }

    fn notify(&self) {
        match &self.scope {
            ScopeStorage::Owned(scope) => (self.on_changed)(scope.as_ref()),
            ScopeStorage::RecomposeScope { weak, .. } => {
                if let Some(inner) = weak.upgrade() {
                    (self.on_changed)(&RecomposeScope { inner });
                }
            }
        }
    }
}

impl ScopeStorage {
    fn from_value<T>(value: T) -> Self
    where
        T: Any + 'static,
    {
        let any = &value as &dyn Any;
        if let Some(scope) = any.downcast_ref::<RecomposeScope>() {
            Self::RecomposeScope {
                id: scope.id(),
                weak: scope.downgrade(),
            }
        } else {
            Self::Owned(Box::new(value))
        }
    }
}

#[cfg(test)]
#[path = "tests/snapshot_state_observer_tests.rs"]
mod tests;