1use super::*;
3use std::any::TypeId;
4use std::borrow::Cow;
5use std::cell::Cell;
6use std::mem::size_of;
7#[path = "sparse.rs"]
8mod sparse;
9use sparse::SparseMap;
10#[path = "entries.rs"]
11mod entries;
12use entries::{EntryIndex, EntryKey};
13#[path = "collections.rs"]
14mod collections;
15
16thread_local! { static PROJECTING: Cell<bool> = const { Cell::new(false) }; }
17pub(super) fn allow_read() -> Result<(), AccessError> {
18 if PROJECTING.get() {
19 Err(AccessError::InvalidField(
20 "reactive reads inside a field accessor",
21 ))
22 } else {
23 Ok(())
24 }
25}
26pub(super) fn project<R>(f: impl FnOnce() -> Result<R, AccessError>) -> Result<R, AccessError> {
27 struct Guard {
28 previous: bool,
29 mode: usize,
30 }
31 impl Drop for Guard {
32 fn drop(&mut self) {
33 PROJECTING.set(self.previous);
34 EVALUATING.with_borrow_mut(|stack| stack.truncate(self.mode));
35 }
36 }
37 let previous = PROJECTING.replace(true);
38 let mode = EVALUATING.with_borrow_mut(|stack| {
39 let n = stack.len();
40 stack.push(Mode::Pure);
41 n
42 });
43 let _guard = Guard { previous, mode };
44 f()
45}
46
47#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
48struct FieldId(Key);
49#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
50enum Parent {
51 Root(Key),
52 Field(FieldId),
53}
54#[derive(Clone, PartialEq, Eq, PartialOrd, Ord)]
55enum Segment {
56 Field(Cow<'static, str>),
57 Item(usize),
58 Entry(u64),
59}
60#[derive(Clone, Copy, PartialEq, Eq)]
61struct Layout {
62 offset: usize,
63 size: usize,
64}
65trait Projection {
66 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError>;
67 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError>;
68}
69struct Map<T, U, G, M> {
70 parent: Option<Rc<dyn Projection>>,
71 get: G,
72 get_mut: M,
73 offset: usize,
74 types: PhantomData<fn(T) -> U>,
75}
76impl<T: 'static, U: 'static, G, M> Projection for Map<T, U, G, M>
77where
78 G: for<'a> Fn(&'a T) -> &'a U,
79 M: for<'a> Fn(&'a mut T) -> &'a mut U,
80{
81 fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
82 let value = if let Some(parent) = &self.parent {
83 parent.read(value)?
84 } else {
85 value
86 };
87 let value = value.downcast_ref::<T>().ok_or(AccessError::TypeMismatch)?;
88 let selected = (self.get)(value);
89 if offset(value, selected)? != self.offset {
90 return Err(AccessError::InvalidField(
91 "field accessor changed its location",
92 ));
93 }
94 Ok(selected)
95 }
96 fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
97 let value = if let Some(parent) = &self.parent {
98 parent.write(value)?
99 } else {
100 value
101 };
102 let value = value.downcast_mut::<T>().ok_or(AccessError::TypeMismatch)?;
103 let start = std::ptr::from_ref(value) as usize;
104 let selected = (self.get_mut)(value);
105 let actual = (std::ptr::from_ref(selected) as usize).checked_sub(start);
106 if actual != Some(self.offset) {
107 return Err(AccessError::InvalidField(
108 "mutable accessor selects another field",
109 ));
110 }
111 Ok(selected)
112 }
113}
114fn offset<T, U>(parent: &T, child: &U) -> Result<usize, AccessError> {
115 let relative = (std::ptr::from_ref(child) as usize)
116 .checked_sub(std::ptr::from_ref(parent) as usize)
117 .ok_or(AccessError::InvalidField(
118 "field is outside its inline parent",
119 ))?;
120 if relative
121 .checked_add(size_of::<U>())
122 .is_none_or(|end| end > size_of::<T>())
123 {
124 return Err(AccessError::InvalidField(
125 "field is outside its inline parent",
126 ));
127 }
128 Ok(relative)
129}
130pub(super) struct FieldData {
131 parent: Parent,
132 root: Key,
133 segment: Segment,
134 output: TypeId,
135 layout: Option<Layout>,
136 depth: usize,
137 projection: Rc<dyn Projection>,
138 children: SparseMap<Segment, FieldId>,
139 aliases: SparseMap<Key, Key>,
141 _entry: Option<Rc<EntryKey>>,
142}
143#[derive(Default)]
144pub(super) struct Fields {
145 roots: BTreeMap<Key, SparseMap<Segment, FieldId>>,
146 slots: Arena<FieldData>,
147 aliases: BTreeMap<Key, FieldId>,
148 indices: BTreeMap<Parent, Rc<EntryIndex>>,
149 targets: BTreeMap<Key, Box<CachedTarget>>,
150}
151#[derive(Default)]
152pub(super) struct Removal {
153 pub aliases: Vec<Key>,
154 pub fields: Vec<FieldData>,
155}
156pub(super) struct ValuePath {
157 pub value: Value,
158 root: Key,
159 projection: Option<Rc<dyn Projection>>,
160}
161impl ValuePath {
162 pub fn read<'a>(&self, value: &'a dyn Any) -> Result<&'a dyn Any, AccessError> {
163 self.projection
164 .as_ref()
165 .map_or(Ok(value), |p| project(|| p.read(value)))
166 }
167 pub fn write<'a>(&self, value: &'a mut dyn Any) -> Result<&'a mut dyn Any, AccessError> {
168 if let Some(p) = &self.projection {
169 project(|| p.write(value))
170 } else {
171 Ok(value)
172 }
173 }
174}
175struct WriteTarget {
176 root: Key,
177 at: Target,
178 nodes: Vec<Key>,
179 pending: Vec<FieldId>,
180}
181#[derive(Clone, Copy, PartialEq, Eq)]
182enum Target {
183 Root,
184 Field(FieldId),
185 Collection,
186}
187#[derive(Clone, Copy, PartialEq, Eq)]
188struct CollectionTarget {
189 parent: Parent,
190 selection: Selection,
191}
192#[derive(Clone, Copy, PartialEq, Eq)]
195enum Selection {
196 Entry(Option<u64>),
197 Items { start: usize, end: usize },
198}
199#[derive(Default)]
200struct CachedTarget {
201 buffer: Option<WriteTarget>,
202 keys: usize,
203 collection: Option<Box<CollectionTarget>>,
206}
207impl Fields {
208 pub fn target_stats(&self) -> (usize, usize) {
209 (
210 self.targets.len(),
211 self.targets.values().map(|target| target.keys).sum(),
212 )
213 }
214 fn invalidate_target(&mut self, root: Key) {
215 self.targets.remove(&root);
219 }
220 pub fn entry_stats(&self) -> (usize, usize) {
221 self.indices
222 .values()
223 .map(|index| index.stats())
224 .fold((0, 0), |a, b| (a.0 + b.0, a.1 + b.1))
225 }
226 pub fn has_root(&self, key: Key) -> bool {
227 self.roots.contains_key(&key)
228 }
229 pub fn len(&self) -> usize {
230 self.slots.len()
231 }
232 pub fn capacity(&self) -> usize {
233 self.slots.capacity()
234 }
235 fn children(&self, parent: Parent) -> Option<&SparseMap<Segment, FieldId>> {
236 match parent {
237 Parent::Root(root) => self.roots.get(&root),
238 Parent::Field(id) => self.slots.get(id.0).map(|f| &f.children),
239 }
240 }
241 fn selected(
242 &self,
243 parent: Parent,
244 selection: Selection,
245 ) -> Option<sparse::Range<'_, Segment, FieldId>> {
246 use std::ops::Bound::{Excluded, Included};
247 let bounds = match selection {
248 Selection::Entry(Some(id)) => {
249 (Included(Segment::Entry(id)), Included(Segment::Entry(id)))
250 }
251 Selection::Entry(None) => return None,
252 Selection::Items { start, end } => {
253 (Included(Segment::Item(start)), Excluded(Segment::Item(end)))
254 }
255 };
256 self.children(parent).map(|children| children.range(bounds))
257 }
258 fn unlink(&mut self, parent: Parent, segment: &Segment) {
259 let empty = match parent {
260 Parent::Root(root) => self.roots.get_mut(&root).is_some_and(|children| {
261 children.remove(segment);
262 children.is_empty()
263 }),
264 Parent::Field(id) => self.slots.get_mut(id.0).is_some_and(|field| {
265 field.children.remove(segment);
266 field.children.is_empty()
267 }),
268 };
269 if empty {
270 self.indices.remove(&parent);
271 if let Parent::Root(root) = parent {
272 self.roots.remove(&root);
273 }
274 }
275 }
276 pub fn detach(&mut self, node: Key, owner: Key) -> Removal {
277 let mut removal = Removal::default();
278 if let Some(mut id) = self.aliases.remove(&node) {
279 if let Some(field) = self.slots.get(id.0) {
280 self.invalidate_target(field.root);
281 }
282 if let Some(field) = self.slots.get_mut(id.0) {
283 field.aliases.remove(&owner);
284 }
285 while let Some(field) = self.slots.get(id.0) {
286 if !field.aliases.is_empty() || !field.children.is_empty() {
287 break;
288 }
289 let field = self.slots.remove(id.0).expect("live field");
290 self.indices.remove(&Parent::Field(id));
291 self.unlink(field.parent, &field.segment);
292 match field.parent {
293 Parent::Root(_) => {
294 removal.fields.push(field);
295 break;
296 }
297 Parent::Field(parent) => {
298 removal.fields.push(field);
299 id = parent;
300 }
301 }
302 }
303 }
304 self.indices.remove(&Parent::Root(node));
305 if let Some(roots) = self.roots.remove(&node) {
306 self.invalidate_target(node);
307 let mut pending: Vec<_> = roots.into_values().collect();
308 while let Some(id) = pending.pop() {
309 if let Some(field) = self.slots.remove(id.0) {
310 self.indices.remove(&Parent::Field(id));
311 pending.extend(field.children.values().copied());
312 for alias in field.aliases.values() {
313 self.aliases.remove(alias);
314 removal.aliases.push(*alias);
315 }
316 removal.fields.push(field);
317 }
318 }
319 }
320 removal
321 }
322}
323impl State {
324 pub(super) fn value_path(&self, key: Key, node: &Node) -> Result<ValuePath, AccessError> {
325 if let Some(value) = &node.value {
326 return Ok(ValuePath {
327 value: value.clone(),
328 root: key,
329 projection: None,
330 });
331 }
332 let id = *self
333 .fields
334 .aliases
335 .get(&key)
336 .ok_or(AccessError::TypeMismatch)?;
337 self.field_path(id)
338 }
339 fn field_path(&self, id: FieldId) -> Result<ValuePath, AccessError> {
340 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
341 let value = self
342 .nodes
343 .get(field.root)
344 .and_then(|n| n.value.clone())
345 .ok_or(AccessError::Disposed)?;
346 Ok(ValuePath {
347 value,
348 root: field.root,
349 projection: Some(field.projection.clone()),
350 })
351 }
352 pub(super) fn advance_source(&mut self, key: Key) {
353 let Some(node) = self.nodes.get_mut(key) else {
354 return;
355 };
356 node.version = node
357 .version
358 .checked_add(1)
359 .expect("source version exhausted");
360 if node.propagated {
361 return;
362 }
363 node.propagated = true;
364 self.pending_invalidations
365 .extend(node.subscribers.iter().copied());
366 self.invalidate();
367 }
368 fn write_target(&mut self, root: Key, at: Target) -> Result<WriteTarget, AccessError> {
369 debug_assert!(!matches!(at, Target::Collection));
370 let cached = self
371 .fields
372 .targets
373 .get(&root)
374 .and_then(|slot| slot.buffer.as_ref());
375 let hit = cached.is_some_and(|target| target.at == at);
376 let mut check = |key| {
379 if let Some(node) = self.nodes.get(key) {
380 node.version
381 .checked_add(1)
382 .expect("source version exhausted");
383 }
384 };
385 if let Some(target) = cached.filter(|_| hit) {
386 for key in &target.nodes {
387 check(*key);
388 }
389 } else {
390 check(root);
391 if let Target::Field(id) = at {
392 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
393 let mut parent = field.parent;
394 while let Parent::Field(id) = parent {
395 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
396 for key in field.aliases.values() {
397 check(*key);
398 }
399 parent = field.parent;
400 }
401 self.visit_target(id, &mut check)?;
402 } else {
403 let children = self
404 .fields
405 .roots
406 .get(&root)
407 .ok_or(AccessError::InvalidField("source has no registered field"))?;
408 for id in children.values() {
409 self.visit_target(*id, &mut check)?;
410 }
411 }
412 }
413 let mut target = self
414 .fields
415 .targets
416 .get_mut(&root)
417 .and_then(|slot| slot.buffer.take())
418 .unwrap_or_else(|| WriteTarget {
419 root,
420 at,
421 nodes: Vec::new(),
422 pending: Vec::new(),
423 });
424 if hit {
425 self.stats.field_target_hits += 1;
426 } else {
427 self.collect_target(root, at, &mut target);
428 self.stats.field_target_builds += 1;
429 self.stats.field_target_visits += target.nodes.len() as u64;
430 }
431 self.fields.targets.entry(root).or_default().keys = target.nodes.len();
434 Ok(target)
435 }
436 fn write_collection_target(
437 &mut self,
438 root: Key,
439 parent: Parent,
440 selection: Selection,
441 ) -> Result<WriteTarget, AccessError> {
442 let selector = CollectionTarget { parent, selection };
443 let slot = self.fields.targets.get(&root);
444 let cached = slot.and_then(|slot| slot.buffer.as_ref());
445 let hit = cached.is_some_and(|target| target.at == Target::Collection)
446 && slot.and_then(|slot| slot.collection.as_deref()) == Some(&selector);
447 let mut check = |key| {
450 if let Some(node) = self.nodes.get(key) {
451 node.version
452 .checked_add(1)
453 .expect("source version exhausted");
454 }
455 };
456 if let Some(target) = cached.filter(|_| hit) {
457 for key in &target.nodes {
458 check(*key);
459 }
460 } else {
461 check(root);
462 let mut ancestor = parent;
463 while let Parent::Field(id) = ancestor {
464 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
465 for key in field.aliases.values() {
466 check(*key);
467 }
468 ancestor = field.parent;
469 }
470 for (_, id) in self
471 .fields
472 .selected(parent, selection)
473 .into_iter()
474 .flatten()
475 {
476 self.visit_target(*id, &mut check)?;
477 }
478 }
479 let mut target = self
480 .fields
481 .targets
482 .get_mut(&root)
483 .and_then(|slot| slot.buffer.take())
484 .unwrap_or_else(|| WriteTarget {
485 root,
486 at: Target::Collection,
487 nodes: Vec::new(),
488 pending: Vec::new(),
489 });
490 if hit {
491 self.stats.field_target_hits += 1;
492 } else {
493 target.root = root;
494 target.at = Target::Collection;
495 target.nodes.clear();
496 target.pending.clear();
497 target.nodes.push(root);
498 let mut ancestor = parent;
499 while let Parent::Field(id) = ancestor {
500 let field = self.fields.slots.get(id.0).expect("prechecked ancestor");
501 target.nodes.extend(field.aliases.values().copied());
502 ancestor = field.parent;
503 }
504 target.pending.extend(
505 self.fields
506 .selected(parent, selection)
507 .into_iter()
508 .flatten()
509 .map(|(_, id)| *id),
510 );
511 while let Some(id) = target.pending.pop() {
512 let field = self.fields.slots.get(id.0).expect("prechecked descendant");
513 target.nodes.extend(field.aliases.values().copied());
514 target.pending.extend(field.children.values().copied());
515 }
516 self.stats.field_target_builds += 1;
517 self.stats.field_target_visits += target.nodes.len() as u64;
518 }
519 let slot = self.fields.targets.entry(root).or_default();
520 slot.keys = target.nodes.len();
521 if !hit {
522 if let Some(previous) = &mut slot.collection {
523 **previous = selector;
524 } else {
525 slot.collection = Some(Box::new(selector));
526 }
527 }
528 Ok(target)
529 }
530 fn visit_target(&self, id: FieldId, visit: &mut impl FnMut(Key)) -> Result<(), AccessError> {
531 let field = self.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
532 for key in field.aliases.values() {
533 visit(*key);
534 }
535 for child in field.children.values() {
537 self.visit_target(*child, visit)?;
538 }
539 Ok(())
540 }
541 fn collect_target(&self, root: Key, at: Target, target: &mut WriteTarget) {
542 target.root = root;
543 target.at = at;
544 target.nodes.clear();
545 target.pending.clear();
546 target.nodes.push(root);
547 if let Target::Field(id) = at {
548 let field = self.fields.slots.get(id.0).expect("prechecked field");
549 let mut parent = field.parent;
550 while let Parent::Field(id) = parent {
551 let field = self.fields.slots.get(id.0).expect("prechecked ancestor");
552 target.nodes.extend(field.aliases.values().copied());
553 parent = field.parent;
554 }
555 target.pending.push(id);
556 } else {
557 target.pending.extend(
558 self.fields
559 .roots
560 .get(&root)
561 .expect("prechecked root")
562 .values()
563 .copied(),
564 );
565 }
566 while let Some(id) = target.pending.pop() {
567 let field = self.fields.slots.get(id.0).expect("prechecked descendant");
568 target.nodes.extend(field.aliases.values().copied());
569 target.pending.extend(field.children.values().copied());
570 }
571 }
572}
573
574struct Write {
575 state: Shared,
576 target: Option<WriteTarget>,
577}
578impl Drop for Write {
579 fn drop(&mut self) {
580 let target = self.target.take().expect("one write guard");
581 let host = {
582 let mut state = self.state.borrow_mut();
583 if state.nodes.get(target.root).is_some() {
584 state.stats.source_writes += 1;
585 for key in &target.nodes {
586 state.advance_source(*key);
587 }
588 }
589 let host = state.host.clone();
590 if let Some(slot) = state.fields.targets.get_mut(&target.root) {
591 slot.buffer = Some(target);
592 }
593 host
594 };
595 if let Some(host) = host {
596 host.wake();
597 }
598 }
599}
600pub(super) fn revise<T: 'static, R>(
603 state: Shared,
604 key: Key,
605 f: impl FnOnce(&mut T) -> R,
606) -> Result<R, AccessError> {
607 let (path, at) = {
608 let state = state.borrow();
609 let node = state.nodes.get(key).ok_or(AccessError::Disposed)?;
610 let (path, at) = if node.value.is_some() {
611 (state.value_path(key, node)?, Target::Root)
612 } else {
613 let id = *state
614 .fields
615 .aliases
616 .get(&key)
617 .ok_or(AccessError::TypeMismatch)?;
618 (state.field_path(id)?, Target::Field(id))
619 };
620 (path, at)
621 };
622 let mut borrowed = path
623 .value
624 .try_borrow_mut()
625 .map_err(|_| AccessError::Borrowed)?;
626 let value = path
627 .write(borrowed.as_mut())?
628 .downcast_mut()
629 .ok_or(AccessError::TypeMismatch)?;
630 let target = state.borrow_mut().write_target(path.root, at)?;
631 let write = Write {
632 state,
633 target: Some(target),
634 };
635 let result = f(value);
636 drop(borrowed);
637 drop(write);
638 Ok(result)
639}
640
641impl<T> Cage<T> {
642 pub fn field<U: 'static>(
663 self,
664 name: impl Into<Cow<'static, str>>,
665 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
666 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
667 ) -> Cage<U> {
668 self.try_field(name, get, get_mut)
669 .expect("create a pure, disjoint inline field on a live Cage")
670 }
671 pub fn try_field<U: 'static>(
672 self,
673 name: impl Into<Cow<'static, str>>,
674 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
675 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
676 ) -> Result<Cage<U>, AccessError> {
677 allow_creation()?;
678 let name = name.into();
679 if name.is_empty() {
680 return Err(AccessError::InvalidField("empty field name"));
681 }
682 let context = Context::new(self.handle.runtime, self.handle.key)?;
683 inline(context, name, get, get_mut)
684 }
685}
686
687fn inline<T: 'static, U: 'static>(
688 context: Context,
689 name: Cow<'static, str>,
690 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
691 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
692) -> Result<Cage<U>, AccessError> {
693 if name.is_empty() {
694 return Err(AccessError::InvalidField("empty field name"));
695 }
696 let selected_offset = {
697 let borrowed = context
698 .path
699 .value
700 .try_borrow()
701 .map_err(|_| AccessError::Borrowed)?;
702 project(|| {
703 let parent = context
704 .path
705 .read(borrowed.as_ref())?
706 .downcast_ref::<T>()
707 .ok_or(AccessError::TypeMismatch)?;
708 offset(parent, get(parent))
709 })?
710 };
711 let parent = context.path.projection.clone();
712 context.register(
713 Segment::Field(name),
714 Some(Layout {
715 offset: selected_offset,
716 size: size_of::<U>(),
717 }),
718 move || {
719 Rc::new(Map::<T, U, _, _> {
720 parent,
721 get,
722 get_mut,
723 offset: selected_offset,
724 types: PhantomData,
725 }) as Rc<dyn Projection>
726 },
727 None,
728 )
729}
730struct PathGuard {
731 state: Shared,
732 id: FieldId,
733}
734impl Drop for PathGuard {
735 fn drop(&mut self) {
736 let removed = {
737 let mut graph = self.state.borrow_mut();
738 let mut removed = Vec::new();
739 let mut id = self.id;
740 while let Some(field) = graph.fields.slots.get(id.0) {
741 if !field.aliases.is_empty() || !field.children.is_empty() {
742 break;
743 }
744 let field = graph.fields.slots.remove(id.0).expect("live path");
745 graph.fields.invalidate_target(field.root);
746 graph.fields.indices.remove(&Parent::Field(id));
747 graph.fields.unlink(field.parent, &field.segment);
748 let parent = field.parent;
749 removed.push(field);
750 match parent {
751 Parent::Field(next) => id = next,
752 Parent::Root(_) => break,
753 }
754 }
755 removed
756 };
757 drop(removed);
758 }
759}
760pub(super) fn keyed_field<T: 'static, U: 'static>(
761 source: Cage<Arena<T>>,
762 key: u64,
763 name: impl Into<Cow<'static, str>>,
764 get: impl for<'a> Fn(&'a T) -> &'a U + 'static,
765 get_mut: impl for<'a> Fn(&'a mut T) -> &'a mut U + 'static,
766) -> Result<Cage<U>, AccessError> {
767 let (context, _guard) = entries::keyed_context(source, key)?;
768 inline(context, name.into(), get, get_mut)
769}
770pub(super) fn update_member<T: 'static, R>(
771 source: Cage<Arena<T>>,
772 id: u64,
773 edit: impl FnOnce(&mut T) -> R,
774) -> Result<R, AccessError> {
775 collections::update_member(source, id, edit)
776}
777pub(super) fn append_members<T: 'static, R>(
778 source: Cage<Arena<T>>,
779 edit: impl FnOnce(&mut Arena<T>) -> R,
780) -> Result<R, AccessError> {
781 collections::append_members(source, edit)
782}
783pub(super) fn remove_member<T: 'static>(
784 source: Cage<Arena<T>>,
785 id: u64,
786) -> Result<Option<T>, AccessError> {
787 collections::remove_member(source, id)
788}
789
790struct Context {
791 state: Shared,
792 runtime: RuntimeId,
793 source: Key,
794 owner: Key,
795 parent: Parent,
796 depth: usize,
797 path: ValuePath,
798}
799impl Context {
800 fn new(runtime: RuntimeId, key: Key) -> Result<Self, AccessError> {
801 allow_creation()?;
802 let state = lookup(runtime)?;
803 let (path, source_owner, parent, depth) = {
804 let graph = state.borrow();
805 let source = graph.nodes.get(key).ok_or(AccessError::Disposed)?;
806 let field = graph.fields.aliases.get(&key).copied();
807 let depth = field
808 .and_then(|id| graph.fields.slots.get(id.0))
809 .map_or(1, |f| f.depth + 1);
810 (
811 graph.value_path(key, source)?,
812 source.owner,
813 field.map_or(Parent::Root(key), Parent::Field),
814 depth,
815 )
816 };
817 if depth > 128 {
818 return Err(AccessError::InvalidField("field nesting exceeds 128"));
819 }
820 drop(path.value.try_borrow().map_err(|_| AccessError::Borrowed)?);
823 let owner = CONSTRUCTING.with_borrow(|stack| {
824 stack
825 .last()
826 .filter(|(r, _)| *r == runtime)
827 .map(|(_, owner)| *owner)
828 .unwrap_or(source_owner)
829 });
830 Ok(Self {
831 state,
832 runtime,
833 source: key,
834 owner,
835 parent,
836 depth,
837 path,
838 })
839 }
840 fn register<U: 'static>(
841 self,
842 segment: Segment,
843 layout: Option<Layout>,
844 projection: impl FnOnce() -> Rc<dyn Projection>,
845 entry: Option<(Rc<EntryKey>, Rc<EntryIndex>)>,
846 ) -> Result<Cage<U>, AccessError> {
847 let id = self.canonical::<U>(segment, layout, projection, entry)?;
848 self.alias(id)
849 }
850 fn canonical<U: 'static>(
851 &self,
852 segment: Segment,
853 layout: Option<Layout>,
854 projection: impl FnOnce() -> Rc<dyn Projection>,
855 entry: Option<(Rc<EntryKey>, Rc<EntryIndex>)>,
856 ) -> Result<FieldId, AccessError> {
857 let mut graph = self.state.borrow_mut();
858 let (owner, parent) = (self.owner, self.parent);
859 if graph.owners.get(owner).is_none() || graph.nodes.get(self.source).is_none() {
860 return Err(AccessError::Disposed);
861 }
862 if let Some((_, index)) = &entry
863 && graph
864 .fields
865 .indices
866 .get(&parent)
867 .is_some_and(|existing| !Rc::ptr_eq(existing, index))
868 {
869 return Err(AccessError::InvalidField(
870 "collection path changed during key comparison",
871 ));
872 }
873 let existing = graph
874 .fields
875 .children(parent)
876 .and_then(|children| children.get(&segment))
877 .copied();
878 let id = if let Some(id) = existing {
879 let field = graph.fields.slots.get(id.0).ok_or(AccessError::Disposed)?;
880 if field.output != TypeId::of::<U>() {
881 return Err(AccessError::TypeMismatch);
882 }
883 if field.layout != layout {
884 return Err(AccessError::InvalidField("same name selects another field"));
885 }
886 id
887 } else {
888 if let Some(siblings) = graph.fields.children(parent) {
889 if let Some(first) = siblings.values().next() {
893 let first = graph
894 .fields
895 .slots
896 .get(first.0)
897 .ok_or(AccessError::Disposed)?;
898 if first.layout.is_some() != layout.is_some() {
899 return Err(AccessError::InvalidField(
900 "inline and collection siblings overlap; use a common parent",
901 ));
902 }
903 }
904 if let Some(b) = layout {
905 for id in siblings.values() {
906 let a = graph
907 .fields
908 .slots
909 .get(id.0)
910 .ok_or(AccessError::Disposed)?
911 .layout
912 .expect("inline siblings");
913 if a.size != 0
914 && b.size != 0
915 && b.offset < a.offset + a.size
916 && a.offset < b.offset + b.size
917 {
918 return Err(AccessError::InvalidField("overlapping sibling fields"));
919 }
920 }
921 }
922 }
923 let id = FieldId(graph.fields.slots.insert(FieldData {
924 parent,
925 root: self.path.root,
926 segment: segment.clone(),
927 output: TypeId::of::<U>(),
928 layout,
929 depth: self.depth,
930 projection: projection(),
933 children: SparseMap::default(),
934 aliases: SparseMap::default(),
935 _entry: entry.as_ref().map(|(key, _)| key.clone()),
936 }));
937 if let Some((_, index)) = &entry {
938 graph
939 .fields
940 .indices
941 .entry(parent)
942 .or_insert_with(|| index.clone());
943 }
944 match parent {
945 Parent::Root(root) => {
946 graph
947 .fields
948 .roots
949 .entry(root)
950 .or_default()
951 .insert(segment, id);
952 }
953 Parent::Field(parent) => {
954 graph
955 .fields
956 .slots
957 .get_mut(parent.0)
958 .expect("live parent")
959 .children
960 .insert(segment, id);
961 }
962 }
963 id
964 };
965 Ok(id)
966 }
967 fn alias<U: 'static>(&self, id: FieldId) -> Result<Cage<U>, AccessError> {
968 let mut graph = self.state.borrow_mut();
969 let owner = self.owner;
970 if graph.owners.get(owner).is_none() || graph.nodes.get(self.source).is_none() {
971 return Err(AccessError::Disposed);
972 }
973 if let Some(key) = graph
974 .fields
975 .slots
976 .get(id.0)
977 .ok_or(AccessError::Disposed)?
978 .aliases
979 .get(&owner)
980 {
981 return Ok(Cage {
982 handle: Handle::new(self.runtime, *key),
983 });
984 }
985 let node = Node {
986 owner,
987 compute: Compute::Source,
988 value: None,
989 version: 1,
990 status: Status::Clean,
991 rerun: false,
992 propagated: false,
993 queued: false,
994 last_flush: 0,
995 flush_runs: 0,
996 dependencies: Dependencies::new(),
997 subscribers: Subscribers::new(),
998 };
999 let key = graph.insert_node(owner, node)?;
1000 graph.fields.aliases.insert(key, id);
1001 graph
1002 .fields
1003 .slots
1004 .get_mut(id.0)
1005 .expect("live field")
1006 .aliases
1007 .insert(owner, key);
1008 graph.fields.invalidate_target(self.path.root);
1009 drop(graph);
1010 Ok(Cage {
1011 handle: Handle::new(self.runtime, key),
1012 })
1013 }
1014}
1015
1016#[cfg(test)]
1017mod cache_tests {
1018 use super::*;
1019 #[test]
1020 fn collection_targets_precheck_selected_versions_and_ignore_unchanged_positions() {
1021 let runtime = Runtime::new();
1022 let owner = runtime.owner();
1023 let rows = owner.cage(vec![0usize]);
1024 let first = rows.item(0);
1025 let last = rows.item(1);
1026 runtime
1027 .state
1028 .borrow_mut()
1029 .nodes
1030 .get_mut(first.handle.key)
1031 .unwrap()
1032 .version = u64::MAX;
1033 rows.push(1); assert_eq!(rows.with(Vec::len), 2);
1035 runtime
1036 .state
1037 .borrow_mut()
1038 .nodes
1039 .get_mut(last.handle.key)
1040 .unwrap()
1041 .version = u64::MAX;
1042 let before = runtime.stats();
1043 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rows.pop())).is_err());
1044 assert_eq!(rows.with(Vec::len), 2);
1045 assert_eq!(runtime.stats(), before);
1046 runtime
1047 .state
1048 .borrow_mut()
1049 .nodes
1050 .get_mut(last.handle.key)
1051 .unwrap()
1052 .version = 1;
1053 rows.pop();
1054 runtime
1055 .state
1056 .borrow_mut()
1057 .nodes
1058 .get_mut(rows.handle.key)
1059 .unwrap()
1060 .version = u64::MAX;
1061 let before = runtime.stats();
1062 assert!(std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| rows.push(2))).is_err());
1063 assert_eq!(rows.with(Vec::len), 1);
1064 assert_eq!(runtime.stats(), before);
1065 }
1066 #[test]
1067 fn cached_targets_still_precheck_every_source_version() {
1068 let runtime = Runtime::new();
1069 let owner = runtime.owner();
1070 let source = owner.cage((0usize,));
1071 let field = source.field("value", |m| &m.0, |m| &mut m.0);
1072 field.revise(|v| *v = 1);
1073 runtime
1074 .state
1075 .borrow_mut()
1076 .nodes
1077 .get_mut(source.handle.key)
1078 .unwrap()
1079 .version = u64::MAX;
1080 let before = runtime.stats();
1081 let called = Cell::new(false);
1082 assert!(
1083 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| field.revise(|v| {
1084 called.set(true);
1085 *v = 2;
1086 })))
1087 .is_err()
1088 );
1089 assert!(!called.get());
1090 assert_eq!(field.get(), 1);
1091 assert_eq!(runtime.stats(), before);
1092 runtime
1093 .state
1094 .borrow_mut()
1095 .nodes
1096 .get_mut(source.handle.key)
1097 .unwrap()
1098 .version = 1;
1099 field.revise(|v| *v = 2);
1100 assert_eq!(
1101 runtime.stats().field_target_hits,
1102 before.field_target_hits + 1
1103 );
1104 }
1105 #[test]
1106 fn borrowed_buffers_return_only_while_their_root_slot_survives() {
1107 let runtime = Runtime::new();
1108 let owner = runtime.owner();
1109 let source = owner.cage((0usize,));
1110 let field = source.field("value", |m| &m.0, |m| &mut m.0);
1111 let row = runtime.owner();
1112 let second = row.enter(|| source.field("value", |m| &m.0, |m| &mut m.0));
1113 let other = owner.cage((0usize,));
1114 second.revise(|v| {
1115 assert!(
1116 runtime.state.borrow().fields.targets[&source.handle.key]
1117 .buffer
1118 .is_none()
1119 );
1120 other
1121 .field("other", |m| &m.0, |m| &mut m.0)
1122 .revise(|n| *n = 1);
1123 assert!(
1124 runtime.state.borrow().fields.targets[&source.handle.key]
1125 .buffer
1126 .is_none()
1127 );
1128 *v = 1;
1129 });
1130 assert_eq!(runtime.stats().field_target_caches, 2);
1131 second.revise(|v| {
1132 drop(row);
1133 *v = 2;
1134 });
1135 assert_eq!(field.get(), 2);
1136 assert!(
1137 !runtime
1138 .state
1139 .borrow()
1140 .fields
1141 .targets
1142 .contains_key(&source.handle.key)
1143 );
1144 assert_eq!(runtime.stats().field_target_caches, 1);
1145 field.revise(|v| *v = 3);
1146 assert_eq!(runtime.stats().field_target_caches, 2);
1147 }
1148 #[test]
1149 fn alternating_selections_reuse_buffers_with_space_bounded_by_live_schema() {
1150 let runtime = Runtime::new();
1151 let owner = runtime.owner();
1152 let source = owner.cage([0usize; 64]);
1153 let mut owners: Vec<_> = (0..64).map(|_| Some(runtime.owner())).collect();
1154 let fields: Vec<_> = (0..64)
1155 .map(|i| {
1156 owners[i]
1157 .as_ref()
1158 .unwrap()
1159 .enter(|| source.field(format!("{i}"), move |m| &m[i], move |m| &mut m[i]))
1160 })
1161 .collect();
1162 source.revise(|m| m.fill(0));
1163 let buffers = || {
1164 let state = runtime.state.borrow();
1165 let buffer = state.fields.targets[&source.handle.key]
1166 .buffer
1167 .as_ref()
1168 .unwrap();
1169 assert!(buffer.pending.is_empty());
1170 assert!(buffer.nodes.capacity() <= 2 * (state.fields.aliases.len() + 1));
1171 assert!(buffer.pending.capacity() <= 2 * state.fields.len());
1172 (buffer.nodes.as_ptr(), buffer.pending.as_ptr())
1173 };
1174 let initial = buffers();
1175 for i in 0..1000 {
1176 fields[i % 64].revise(|v| *v += 1);
1177 assert_eq!(buffers(), initial);
1178 assert_eq!(
1179 (
1180 runtime.stats().field_target_caches,
1181 runtime.stats().field_target_keys
1182 ),
1183 (1, 2)
1184 );
1185 }
1186 assert_eq!(source.with(|m| m.iter().sum::<usize>()), 1000);
1187 drop(owners[0].take());
1188 assert_eq!(
1189 (
1190 runtime.stats().field_target_caches,
1191 runtime.stats().field_target_keys
1192 ),
1193 (0, 0)
1194 );
1195 }
1196}