Skip to main content

cranpose_core/snapshot_v2/
transparent.rs

1use super::*;
2
3/// A transparent mutable snapshot that allows observer replacement.
4///
5/// This snapshot type is optimized for cases where observers need to be
6/// temporarily added or removed without creating a new snapshot structure.
7///
8/// # Thread Safety
9/// Contains `Cell<T>` and `RefCell<T>` which are not `Send`/`Sync`. This is safe because
10/// snapshots are stored in thread-local storage and never shared across threads. The `Rc`
11/// is used for cheap cloning within a single thread, not for cross-thread sharing.
12pub struct TransparentObserverMutableSnapshot {
13    pub(super) state: SnapshotState,
14    parent: Option<Weak<Self>>,
15    nested_count: Cell<usize>,
16    applied: Cell<bool>,
17    reusable: Cell<bool>,
18}
19
20impl TransparentObserverMutableSnapshot {
21    /// Creates a transparent mutable snapshot with the given id and invalid set. The observers are
22    /// called for reads and writes inside it and can be replaced later. `parent` is the snapshot it
23    /// was taken from, if that snapshot is still alive.
24    pub fn new(
25        id: SnapshotId,
26        invalid: SnapshotIdSet,
27        read_observer: Option<ReadObserver>,
28        write_observer: Option<WriteObserver>,
29        parent: Option<Weak<Self>>,
30    ) -> Rc<Self> {
31        Self::new_reusing(None, id, invalid, read_observer, write_observer, parent)
32    }
33
34    pub(crate) fn new_reusing(
35        recycled: Option<Rc<Self>>,
36        id: SnapshotId,
37        invalid: SnapshotIdSet,
38        read_observer: Option<ReadObserver>,
39        write_observer: Option<WriteObserver>,
40        parent: Option<Weak<Self>>,
41    ) -> Rc<Self> {
42        // A recycled snapshot is set up again field by field: building a new
43        // value and moving it in copies it whole.
44        if let Some(mut recycled) = recycled
45            && let Some(target) = Rc::get_mut(&mut recycled)
46        {
47            target
48                .state
49                .restart_unpinned(id, invalid, read_observer, write_observer);
50            target.parent = parent;
51            *target.nested_count.get_mut() = 0;
52            *target.applied.get_mut() = false;
53            *target.reusable.get_mut() = true;
54            return recycled;
55        }
56        Rc::new(Self {
57            state: SnapshotState::new_with_pinning(
58                id,
59                invalid,
60                read_observer,
61                write_observer,
62                RuntimeTracking::Untracked,
63                Pinning::Unpinned,
64            ),
65            parent,
66            nested_count: Cell::new(0),
67            applied: Cell::new(false),
68            reusable: Cell::new(true),
69        })
70    }
71
72    /// Check if this snapshot can be reused for observer changes.
73    pub fn can_reuse(&self) -> bool {
74        self.reusable.get()
75    }
76
77    pub(crate) fn observers(&self) -> (Option<ReadObserver>, Option<WriteObserver>) {
78        (
79            self.state.read_observer.borrow().clone(),
80            self.state.write_observer.borrow().clone(),
81        )
82    }
83
84    pub(crate) fn reads_into(&self, observer: &ReadObserver) -> bool {
85        self.state
86            .read_observer
87            .borrow()
88            .as_ref()
89            .is_some_and(|installed| Rc::ptr_eq(installed, observer))
90    }
91
92    /// Set the read observer (only allowed if reusable).
93    pub fn set_read_observer(&self, observer: Option<ReadObserver>) {
94        assert!(
95            self.can_reuse(),
96            "Cannot change observers on non-reusable snapshot"
97        );
98        *self.state.read_observer.borrow_mut() = observer;
99    }
100
101    /// Set the write observer (only allowed if reusable).
102    pub fn set_write_observer(&self, observer: Option<WriteObserver>) {
103        assert!(
104            self.can_reuse(),
105            "Cannot change observers on non-reusable snapshot"
106        );
107        *self.state.write_observer.borrow_mut() = observer;
108    }
109
110    /// Returns the id of this snapshot. Ids grow with every snapshot taken.
111    pub fn snapshot_id(&self) -> SnapshotId {
112        self.state.id.get()
113    }
114
115    /// Returns the ids of snapshots whose writes this snapshot does not see.
116    pub fn invalid(&self) -> SnapshotIdSet {
117        self.state.invalid.borrow().clone()
118    }
119
120    /// Returns `false`: this snapshot accepts writes.
121    pub fn read_only(&self) -> bool {
122        false
123    }
124
125    /// Returns the outermost parent that is still alive, or this snapshot when it has none.
126    pub fn root_transparent_mutable(self: &Rc<Self>) -> Rc<Self> {
127        match &self.parent {
128            Some(weak) => weak.upgrade().map_or_else(
129                || Rc::clone(self),
130                |parent| parent.root_transparent_mutable(),
131            ),
132            None => Rc::clone(self),
133        }
134    }
135
136    /// Runs `f` with this snapshot as the current snapshot of the thread and returns its result. If
137    /// this snapshot is already current, `f` runs directly. The previous current snapshot is
138    /// restored when `f` returns.
139    pub fn enter<T>(self: &Rc<Self>, f: impl FnOnce() -> T) -> T {
140        let prev = current_snapshot();
141
142        if let Some(ref snapshot) = prev
143            && snapshot.is_same_transparent(self)
144        {
145            return f();
146        }
147
148        enter_snapshot_scope(AnySnapshot::TransparentMutable(Rc::clone(self)), f)
149    }
150
151    /// Takes a read-only snapshot of this snapshot's view of state. Reads inside the new snapshot
152    /// call both `read_observer` and this snapshot's own read observer.
153    pub fn take_nested_snapshot(
154        &self,
155        read_observer: Option<ReadObserver>,
156    ) -> Rc<ReadonlySnapshot> {
157        let merged_observer =
158            merge_read_observers(read_observer, self.state.read_observer.borrow().clone());
159        ReadonlySnapshot::new(
160            self.state.id.get(),
161            self.state.invalid.borrow().clone(),
162            merged_observer,
163        )
164    }
165
166    /// Returns `true` when this snapshot recorded writes that were not applied yet.
167    pub fn has_pending_changes(&self) -> bool {
168        !self.state.modified.borrow().is_empty()
169    }
170
171    /// Releases the snapshot. Does nothing if it was already disposed or if nested snapshots taken
172    /// from it are still open.
173    pub fn dispose(&self) {
174        if !self.state.disposed.get() && self.nested_count.get() == 0 {
175            self.state.dispose();
176        }
177    }
178
179    /// Calls the read observer, if any, with `state`.
180    pub fn record_read(&self, state: &dyn StateObject) {
181        self.state.record_read(state);
182    }
183
184    /// Records `state` as written in this snapshot. The write observer, if any, is called the first
185    /// time a state object is recorded. Panics if the snapshot was applied.
186    pub fn record_write(&self, state: Rc<dyn StateObject>) {
187        assert!(!self.applied.get(), "Cannot write to an applied snapshot");
188        self.state.record_write(state, self.state.id.get());
189    }
190
191    /// Returns `true` once the snapshot was disposed.
192    pub fn is_disposed(&self) -> bool {
193        self.state.disposed.get()
194    }
195
196    /// Marks the snapshot as applied. Returns `Failure` if it was already applied or disposed.
197    pub fn apply(&self) -> SnapshotApplyResult {
198        if self.state.disposed.get() || self.applied.get() {
199            return SnapshotApplyResult::Failure;
200        }
201
202        self.applied.set(true);
203        SnapshotApplyResult::Success
204    }
205
206    /// Takes a transparent mutable snapshot nested in this one. Reads and writes inside it call
207    /// both the given observers and this snapshot's own observers.
208    pub fn take_nested_mutable_snapshot(
209        &self,
210        read_observer: Option<ReadObserver>,
211        write_observer: Option<WriteObserver>,
212    ) -> Rc<Self> {
213        let merged_read =
214            merge_read_observers(read_observer, self.state.read_observer.borrow().clone());
215        let merged_write =
216            merge_write_observers(write_observer, self.state.write_observer.borrow().clone());
217
218        let mut invalid = self.state.invalid.borrow().clone();
219        let new_id = self.state.id.get().next();
220        invalid = invalid.set(new_id);
221
222        Self::new(
223            new_id,
224            invalid,
225            merged_read,
226            merged_write,
227            self.parent.clone(),
228        )
229    }
230}
231
232/// A transparent read-only snapshot.
233///
234/// Similar to TransparentObserverMutableSnapshot but for read-only snapshots.
235///
236/// # Thread Safety
237/// Contains `Cell<T>` and `RefCell<T>` which are not `Send`/`Sync`. This is safe because
238/// snapshots are stored in thread-local storage and never shared across threads. The `Rc`
239/// is used for cheap cloning within a single thread, not for cross-thread sharing.
240pub struct TransparentObserverSnapshot {
241    pub(super) state: SnapshotState,
242    parent: Option<Weak<Self>>,
243    reusable: Cell<bool>,
244}
245
246impl TransparentObserverSnapshot {
247    /// Creates a transparent read-only snapshot with the given id and invalid set. `read_observer`
248    /// is called for reads inside it and can be replaced later. `parent` is the snapshot it was
249    /// taken from, if that snapshot is still alive.
250    pub fn new(
251        id: SnapshotId,
252        invalid: SnapshotIdSet,
253        read_observer: Option<ReadObserver>,
254        parent: Option<Weak<Self>>,
255    ) -> Rc<Self> {
256        Rc::new(Self {
257            state: SnapshotState::new_with_pinning(
258                id,
259                invalid,
260                read_observer,
261                None,
262                RuntimeTracking::Untracked,
263                Pinning::Unpinned,
264            ),
265            parent,
266            reusable: Cell::new(true),
267        })
268    }
269
270    /// Check if this snapshot can be reused for observer changes.
271    pub fn can_reuse(&self) -> bool {
272        self.reusable.get()
273    }
274
275    /// Set the read observer (only allowed if reusable).
276    pub fn set_read_observer(&self, observer: Option<ReadObserver>) {
277        assert!(
278            self.can_reuse(),
279            "Cannot change observers on non-reusable snapshot"
280        );
281        *self.state.read_observer.borrow_mut() = observer;
282    }
283
284    /// Returns the id of this snapshot. Ids grow with every snapshot taken.
285    pub fn snapshot_id(&self) -> SnapshotId {
286        self.state.id.get()
287    }
288
289    /// Returns the ids of snapshots whose writes this snapshot does not see.
290    pub fn invalid(&self) -> SnapshotIdSet {
291        self.state.invalid.borrow().clone()
292    }
293
294    /// Returns `true`: this snapshot rejects writes.
295    pub fn read_only(&self) -> bool {
296        true
297    }
298
299    /// Returns the outermost parent that is still alive, or this snapshot when it has none.
300    pub fn root_transparent_readonly(self: &Rc<Self>) -> Rc<Self> {
301        match &self.parent {
302            Some(weak) => weak.upgrade().map_or_else(
303                || Rc::clone(self),
304                |parent| parent.root_transparent_readonly(),
305            ),
306            None => Rc::clone(self),
307        }
308    }
309
310    /// Runs `f` with this snapshot as the current snapshot of the thread and returns its result. If
311    /// this snapshot is already current, `f` runs directly. The previous current snapshot is
312    /// restored when `f` returns.
313    pub fn enter<T>(self: &Rc<Self>, f: impl FnOnce() -> T) -> T {
314        let previous = current_snapshot();
315
316        if let Some(ref prev_snapshot) = previous
317            && prev_snapshot.is_same_transparent_readonly(self)
318        {
319            return f();
320        }
321
322        enter_snapshot_scope(AnySnapshot::TransparentReadonly(Rc::clone(self)), f)
323    }
324
325    /// Takes another transparent read-only snapshot with the same view of state. Reads inside the
326    /// new snapshot call both `read_observer` and this snapshot's own read observer.
327    pub fn take_nested_snapshot(&self, read_observer: Option<ReadObserver>) -> Rc<Self> {
328        let merged_observer =
329            merge_read_observers(read_observer, self.state.read_observer.borrow().clone());
330        Self::new(
331            self.state.id.get(),
332            self.state.invalid.borrow().clone(),
333            merged_observer,
334            self.parent.clone(),
335        )
336    }
337
338    /// Returns `false`: a read-only snapshot has no writes.
339    pub fn has_pending_changes(&self) -> bool {
340        false
341    }
342
343    /// Releases the snapshot. Call it once the snapshot is no longer needed.
344    pub fn dispose(&self) {
345        self.state.dispose();
346    }
347
348    /// Calls the read observer, if any, with `state`.
349    pub fn record_read(&self, state: &dyn StateObject) {
350        self.state.record_read(state);
351    }
352
353    /// Always panics: a read-only snapshot rejects writes.
354    pub fn record_write(&self, _state: Rc<dyn StateObject>) {
355        panic!("Cannot write to a read-only snapshot");
356    }
357
358    /// Returns `true` once the snapshot was disposed.
359    pub fn is_disposed(&self) -> bool {
360        self.state.disposed.get()
361    }
362}
363
364#[cfg(test)]
365#[path = "tests/transparent_tests.rs"]
366mod tests;