1use 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 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 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 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
262macro_rules! map_edits {
265 ($map:ty, [$($generic:tt)*]) => {
266 impl<$($generic)*> Cage<$map> {
267 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 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 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 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 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]);