Skip to main content

glory_core/
collections.rs

1//! Explicit structural edits select affected logical paths before modifying the
2//! collection. Arbitrary `revise` remains conservative. No source/history scan.
3use super::*;
4use std::collections::{BTreeMap, HashMap};
5use std::hash::{BuildHasher, Hash};
6
7enum Plan<P, R> {
8    Change(Selection, P),
9    Noop(R),
10}
11enum Publish {
12    Plain { _guard: crate::runtime::Write },
13    Selected { _guard: Write },
14}
15fn mutate<C: 'static, P, R>(
16    cage: Cage<C>,
17    prepare: impl FnOnce(&C, Option<&EntryIndex>) -> Result<Plan<P, R>, AccessError>,
18    edit: impl FnOnce(&mut C, P) -> R,
19) -> Result<R, AccessError> {
20    if EVALUATING.with_borrow(|stack| stack.last().is_some_and(|mode| *mode == Mode::Pure)) {
21        return Err(AccessError::WriteDuringCompute);
22    }
23    let state = lookup(cage.handle.runtime)?;
24    let (path, parent, index) = {
25        let graph = state.borrow();
26        let node = graph
27            .nodes
28            .get(cage.handle.key)
29            .ok_or(AccessError::Disposed)?;
30        if !matches!(node.compute, Compute::Source) {
31            return Err(AccessError::TypeMismatch);
32        }
33        let parent = graph
34            .fields
35            .aliases
36            .get(&cage.handle.key)
37            .copied()
38            .map_or(Parent::Root(cage.handle.key), Parent::Field);
39        (
40            graph.value_path(cage.handle.key, node)?,
41            parent,
42            graph.fields.indices.get(&parent).cloned(),
43        )
44    };
45    let mut borrowed = path
46        .value
47        .try_borrow_mut()
48        .map_err(|_| AccessError::Borrowed)?;
49    let value = path
50        .write(borrowed.as_mut())?
51        .downcast_mut::<C>()
52        .ok_or(AccessError::TypeMismatch)?;
53    // User comparisons/hashing run here, outside graph/index borrows. They may
54    // retire Owners, so revalidate the source before taking a publication guard.
55    let (selection, plan) = match prepare(value, index.as_deref())? {
56        Plan::Noop(result) => {
57            if state.borrow().nodes.get(cage.handle.key).is_none() {
58                return Err(AccessError::Disposed);
59            }
60            return Ok(result);
61        }
62        Plan::Change(selection, plan) => (selection, plan),
63    };
64    let publish = {
65        let mut graph = state.borrow_mut();
66        let source = graph
67            .nodes
68            .get(cage.handle.key)
69            .ok_or(AccessError::Disposed)?;
70        source
71            .version
72            .checked_add(1)
73            .expect("source version exhausted");
74        if matches!(parent, Parent::Root(_)) && !graph.fields.has_root(path.root) {
75            Publish::Plain {
76                _guard: crate::runtime::Write {
77                    state: state.clone(),
78                    key: path.root,
79                },
80            }
81        } else {
82            let target = graph.write_collection_target(path.root, parent, selection)?;
83            Publish::Selected {
84                _guard: Write {
85                    state: state.clone(),
86                    target: Some(target),
87                },
88            }
89        }
90    };
91    let result = edit(value, plan);
92    drop(borrowed);
93    drop(publish);
94    Ok(result)
95}
96fn selected<K: Eq + Hash + 'static>(
97    index: Option<&EntryIndex>,
98    key: &K,
99) -> Result<Selection, AccessError> {
100    Ok(Selection::Entry(
101        index.map(|index| index.find(key)).transpose()?.flatten(),
102    ))
103}
104pub(super) fn update_member<T: 'static, R>(
105    source: Cage<Arena<T>>,
106    id: u64,
107    edit: impl FnOnce(&mut T) -> R,
108) -> Result<R, AccessError> {
109    let key = Key::unpack(id);
110    mutate(
111        source,
112        |arena, _| {
113            if arena.get(key).is_none() {
114                return Err(AccessError::MissingField);
115            }
116            Ok(Plan::Change(Selection::Entry(Some(id)), ()))
117        },
118        |arena, ()| edit(arena.get_mut(key).expect("validated member")),
119    )
120}
121pub(super) fn append_members<T: 'static, R>(
122    source: Cage<Arena<T>>,
123    edit: impl FnOnce(&mut Arena<T>) -> R,
124) -> Result<R, AccessError> {
125    mutate(
126        source,
127        |_, _| Ok(Plan::Change(Selection::Entry(None), ())),
128        |arena, ()| edit(arena),
129    )
130}
131pub(super) fn remove_member<T: 'static>(
132    source: Cage<Arena<T>>,
133    id: u64,
134) -> Result<Option<T>, AccessError> {
135    mutate(
136        source,
137        |arena, _| {
138            Ok(if arena.get(Key::unpack(id)).is_none() {
139                Plan::Noop(None)
140            } else {
141                Plan::Change(Selection::Entry(Some(id)), ())
142            })
143        },
144        |arena, ()| arena.remove(Key::unpack(id)),
145    )
146}
147fn items(start: usize, end: usize) -> Selection {
148    Selection::Items { start, end }
149}
150
151impl<T: 'static> Cage<Vec<T>> {
152    /// Append without notifying old positions. No element/collection Clone.
153    /// `try_` reports reactive access/index/length errors; allocation and user
154    /// destructor panics have the same behavior as ordinary Vec operations.
155    ///
156    /// ```
157    /// let runtime = glory_core::Runtime::new();
158    /// let owner = runtime.owner();
159    /// let rows = owner.cage(Vec::<usize>::new());
160    /// let first = rows.item(0);
161    /// rows.push(7);
162    /// rows.insert(0, 9);
163    /// assert_eq!(first.get(), 9);
164    /// assert_eq!(rows.remove(0), 9);
165    /// assert_eq!(first.get(), 7);
166    /// ```
167    pub fn push(self, value: T) {
168        self.try_push(value).expect("append to a live Vec Cage");
169    }
170    pub fn try_push(self, value: T) -> Result<(), AccessError> {
171        mutate(
172            self,
173            |v, _| {
174                Ok(Plan::Change(
175                    items(
176                        v.len(),
177                        v.len().checked_add(1).ok_or(AccessError::Capacity)?,
178                    ),
179                    (),
180                ))
181            },
182            |v, ()| v.push(value),
183        )
184    }
185    pub fn pop(self) -> Option<T> {
186        self.try_pop().expect("pop a live Vec Cage")
187    }
188    pub fn try_pop(self) -> Result<Option<T>, AccessError> {
189        mutate(
190            self,
191            |v, _| {
192                Ok(if v.is_empty() {
193                    Plan::Noop(None)
194                } else {
195                    Plan::Change(items(v.len() - 1, v.len()), ())
196                })
197            },
198            |v, ()| v.pop(),
199        )
200    }
201    /// Insert at a position; only registered positions in [index, old_len]
202    /// change. Positions are not stable entity identities; use map keys for that.
203    pub fn insert(self, index: usize, value: T) {
204        self.try_insert(index, value)
205            .expect("insert within a live Vec Cage");
206    }
207    pub fn try_insert(self, index: usize, value: T) -> Result<(), AccessError> {
208        mutate(
209            self,
210            |v, _| {
211                if index > v.len() {
212                    return Err(AccessError::OutOfBounds);
213                }
214                Ok(Plan::Change(
215                    items(index, v.len().checked_add(1).ok_or(AccessError::Capacity)?),
216                    (),
217                ))
218            },
219            |v, ()| v.insert(index, value),
220        )
221    }
222    pub fn remove(self, index: usize) -> T {
223        self.try_remove(index)
224            .expect("remove within a live Vec Cage")
225    }
226    pub fn try_remove(self, index: usize) -> Result<T, AccessError> {
227        mutate(
228            self,
229            |v, _| {
230                if index >= v.len() {
231                    return Err(AccessError::OutOfBounds);
232                }
233                Ok(Plan::Change(items(index, v.len()), ()))
234            },
235            |v, ()| v.remove(index),
236        )
237    }
238    pub fn truncate(self, len: usize) {
239        self.try_truncate(len).expect("truncate a live Vec Cage");
240    }
241    pub fn try_truncate(self, len: usize) -> Result<(), AccessError> {
242        mutate(
243            self,
244            |v, _| {
245                Ok(if len >= v.len() {
246                    Plan::Noop(())
247                } else {
248                    Plan::Change(items(len, v.len()), ())
249                })
250            },
251            |v, ()| v.truncate(len),
252        )
253    }
254    pub fn clear(self) {
255        self.truncate(0);
256    }
257    pub fn try_clear(self) -> Result<(), AccessError> {
258        self.try_truncate(0)
259    }
260}
261
262// Keep identical edit/notification semantics for both standard map families.
263// These are Rust API code generation, not a UI or expression DSL.
264macro_rules! map_edits {
265    ($map:ty, [$($generic:tt)*]) => {
266        impl<$($generic)*> Cage<$map> {
267            /// Edit one present key without constructing a persistent entry alias.
268            /// Only that key's registered fields and map/ancestor readers publish.
269            pub fn try_update<R>(self, key: &K, edit: impl FnOnce(&mut V) -> R) -> Result<R, AccessError> {
270                mutate(self, |map, index| {
271                    if !project(|| Ok(map.contains_key(key)))? { return Err(AccessError::MissingField); }
272                    Ok(Plan::Change(selected(index,key)?, ()))
273                }, |map, ()| edit(project(||Ok(map.get_mut(key))).expect("pure map lookup").expect("validated present key")))
274            }
275            /// Insert/replace one key. Publishes the map/ancestors and that key's
276            /// live aliases/children; unrelated keys are not invalidated. Keys
277            /// and values need not be Clone. Hash/Eq/Ord/hasher must be pure.
278            ///
279            /// ```
280            /// let runtime = glory_core::Runtime::new();
281            /// let owner = runtime.owner();
282            /// let rows = owner.cage(std::collections::HashMap::<u64, String>::new());
283            /// let title = rows.entry(7);
284            /// assert_eq!(title.try_get(), Err(glory_core::AccessError::MissingField));
285            /// rows.insert(7, String::from("ready"));
286            /// assert_eq!(title.get(), "ready");
287            /// assert_eq!(rows.remove(&7).as_deref(), Some("ready"));
288            /// ```
289            pub fn insert(self, key: K, value: V) -> Option<V> {
290                self.try_insert(key,value).expect("insert into a live map Cage")
291            }
292            pub fn try_insert(self, key: K, value: V) -> Result<Option<V>, AccessError> {
293                // Retain a duplicate incoming key until the mutable model borrow
294                // and publication have ended, so its destructor can use runtime.
295                let (old,duplicate)=mutate(self, |_, index| Ok(Plan::Change(selected(index,&key)?, key)), |map, key| {
296                    if let Some(old)=project(|| Ok(map.get_mut(&key))).expect("pure map lookup") {
297                        (Some(std::mem::replace(old,value)),Some(key))
298                    } else {
299                        (project(|| Ok(map.insert(key,value))).expect("pure map insertion"),None)
300                    }
301                })?;
302                drop(duplicate);
303                Ok(old)
304            }
305            /// Missing-key removal is a no-op (no versions, work or wake).
306            pub fn remove(self, key: &K) -> Option<V> {
307                self.try_remove(key).expect("remove from a live map Cage")
308            }
309            pub fn try_remove(self, key: &K) -> Result<Option<V>, AccessError> {
310                let removed=mutate(self, |map, index| {
311                    if !project(|| Ok(map.contains_key(key)))? { return Ok(Plan::Noop(None)); }
312                    Ok(Plan::Change(selected(index,key)?, ()))
313                }, |map, ()| project(|| Ok(map.remove_entry(key))).expect("pure map removal"))?;
314                // A removed stored key drops outside graph, registry and model
315                // borrows, rather than in the middle of std::Map::remove.
316                Ok(removed.map(|(_,value)| value))
317            }
318        }
319    };
320}
321map_edits!(BTreeMap<K,V>, [K: Ord + Hash + 'static, V: 'static]);
322map_edits!(HashMap<K,V,S>, [K: Eq + Hash + 'static, V: 'static, S: BuildHasher + 'static]);